i have pieced together a post grid loop with AJAX Load More button for posts from a CPT category but I cant get the offset to work properly. There are supposed to be 6 posts per page but at the moment it loads the next 6 posts in random order and duplicates some of them. Also I need the button to disappear when there are no more posts to load, i cant find how to do this anywhere!
Template code:
<?php
$postsPerPage = 6;
$args = array(
'post_status' => 'publish',
'post_type' => 'ce_project',
'posts_per_page' => $postsPerPage,
'offset' => $offset,
'category_name' => 'branding',
'order' => 'DESC'
); ?>
<div class="tabgrid">
<?php $loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<?php get_template_part( 'template-parts/content-postgrid' ); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</div>
<div class="loadmore-row"><a id="more_posts"></a></div>
Functions.php:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'ce_project',
'posts_per_page' => $ppp,
'offset' => $offset,
'order' => 'DESC'
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
get_template_part( 'template-parts/content-postgrid' );
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
JS:
jQuery(document).ready(function($){
var ajaxUrl = "http://example.com/wp-admin/admin-ajax.php";
var page = 1; // What page we are on.
var ppp = 6; // 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,
ppp: ppp
}).success(function(posts){
page++;
$(".tabgrid").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
});