Wordpress- Ajax Pagination (How to implement pagination on a custom WP_Query Ajax ?)

Question: How can we implement pagination on a custom WP_Query Ajax ?

Answer: We can follow the following steps.

1. Load More link.

1
<a id="more_posts" href="#">Load More</a>

2. Javascript: - Put this at the bottom of the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var ajaxUrl = "<!--php echo admin_url('admin-ajax.php')?-->";
 var page = 1; // What page we are on.
 var ppp = 3; // Post per page
 
 $("#more_posts").on("click",function(){ // When btn is pressed.
     $("#more_posts").attr("disabled",true); // Disable the button, temp.
     $.post(ajaxUrl, {
         action:"more_post_ajax",
        // offset: (page * ppp) + 1,
         offset: (page * ppp),
         ppp: ppp
     }).success(function(posts){
         page++;
         $(".name_of_posts_class").append(posts); // CHANGE THIS!
         $("#more_posts").attr("disabled",false);
     });
});

3. Put this in the functions.php file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");
 
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 1,
        'offset' => $offset,
    );
 
    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post();
       the_content();
    }
 
    exit;
}
 
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

4. Enjoy :)

No comments:

Post a Comment