Can't get next post info with ajax

by bilimokur   Last Updated July 15, 2018 19:08 PM

I am trying to get next post id with ajax. Here is my ajax function.

$('.gallery-next').click(function(){
    var currenturl = window.location.href;

    var button = $(this),
        data = {
            'action': 'gallery',
            'curl': currenturl, // send current url to ajax function
        };

    $.ajax({
        url: ajax_params.ajaxurl,
        data: data,
        dataType: 'json',
        type: 'POST',
        beforeSend : function ( xhr) {

        },
        success : function ( response ) {
            alert(response.nextImageSrc);
            alert(response.nextUrl);
        }
    })

});

functions.php

function gallery() {
    // Get current url from ajax.js
    $currentPostUrl = $_POST['curl'];

    // Convert url to id
    $currentPostID = url_to_postid( $currentPostUrl );

    //Load post by id
    global $post;
    $post = get_post($currentPostID);

    // Get next post id
    $nextPostID = get_next_post()->ID;
    // Get next post url
    $nextPostUrl = get_the_permalink($nextPostID);

    // Get post's attachment image src by id
    $nextPostImageSrc = wp_get_attachment_image_src($nextPostID, 'fulll')[0];

    // Send args to response
    echo json_encode( [ 'nextUrl' => $nextPostUrl, 'nextImageSrc' => $nextPostImageSrc] );

    die();
}
add_action('wp_ajax_gallery', 'gallery');
add_action('wp_ajax_nopriv_gallery', 'gallery');

I think all is good. But i can't get next post info. Where i am wrong?

Tags : ajax jquery


Related Questions




Jquery not appearing on homepage

Updated January 22, 2018 07:08 AM