How to implement AJAX post navigation into WordPress?

What you are looking for is AJAX navigation. It’s not that complicated, however it’s not very easy too. I’ve written a simple example for you, I hope it helps you in your case.

An AJAX request has 2 steps, first a front-end request that is sent out by browser when for example a user clicks a link or an element, then a response from the server.

If we need to use that response in our website, there is a third step, which is, well… which is using the response in our website!

Creating an AJAX request on user’s demand

If our user clicks a link, we have to stop the browser to navigating to that page. We can achieve this by using a jQuery function, called preventDefault(). This will prevent the default action of any element that is bound to it, whether it’s a form, or a link.

We need to build some custom link, to make sure we don’t interfere with other links such as social networks. We’ll add a class and an attribute to our navigation links to use it in the AJAX request.

To get the next post’s data, we use get_next_post(); and get_previous_post();. We need the ID too. So:

$next_post = get_next_post();
$prev_post = get_previous_post();
// Check if the post exists
if ( $prev_post ) { ?>
    <div class="prev ajax-link" data-id="<?php echo $prev_post->ID; ?>"><?php _e('&laquo; Previous Posts','text-domain'); ?></div><?php
}
if ( $next_post ) { ?>
    <div class="next ajax-link" data-id="<?php echo $next_post->ID; ?>"><?php _e('Newer Posts &raquo;','text-domain'); ?></div><?php
}

Now, we’ll write a jQuery function and disable the click event on our custom link:

(function($){
    $('.ajax-link').on('click',function(e){
        e.preventDefault();
        // The rest of the code goes here, check below
    });
})(jQuery);

By using $(this) we get the ID of the post which we saved previously in the data-id:

var postId = $(this).attr('data-id');

Okay now we have the ID, let’s create an AJAX request to out yet not written REST endpoint, and put the response in a DIV that is used as the container of our content:

$.get( 'http://example.com/prisma/ajax_navigation/', {
    ajaxid: postId
}).done( function( response ) {
    if ( response.success ) {
        $( '#content-div' ).innerHTML( response.content );
    }
});

Which content-div is the ID of the DIV that holds your content. It’s the element’s ID, not the class, and must be unique in the entire page. Alright, time to write the server side endpoint.

Creating a REST endpoint to return the post’s data

Creating a REST endpoint is as easy as the next lines:

add_action( 'rest_api_init', function () {
    //Path to AJAX endpoint
    register_rest_route( 'prisma', '/ajax_navigation/', array(
            'methods' => 'GET', 
            'callback' => 'ajax_navigation_function' 
    ) );
});

We’ve made an endpoint at http://example.com/prisma/ajax_navigation/. The path is accessible now, but we still need a callback function to return the post’s data.

function ajax_navigation_function(){
    if( isset( $_REQUEST['ajaxid'] ) ){
        $post = get_post( $_REQUEST['ajaxid'] );
        $data['content'] = $post->post_content;
        $data['success'] =  true;
        return $data;
    }
}

That’s it. Now whenever a user clicks the next post or previous post element, the content of the next or previous post will be fetched via AJAX, and inserted into the DIV element that has the ID of content-div.

All done.

Leave a Comment