I'm trying to load posts via AJAX, but while the code below works on page load, after the initial 8 posts, the return is everything. This doesn't seem to make sense as to why on page load it would work, then subsequent requests are then returning so many results.
The query is for multiple categories of the same post type, the category ID is obtained when clicking a tab (which works fine):
var cat = jQuery(this).attr("id");
Is there something obvious I'm missing here?
// HTML
<div class="aj_load">Loading...</div>
<div id="data"></div>
// AJAX Posts (on the page)
var pageNumber = '1';
function load_posts(){
var cat = jQuery("#tabs li.active").attr("id");
jQuery(".aj_load").animate({'opacity' : 1}, 300);
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&action=load_more';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data: str,
success: function(data){
var jQuerydata = jQuery(data);
if(jQuerydata.length){
jQuery(".aj_load").animate({'opacity' : 0}, 300);
jQuery("#data").append(jQuerydata);
}
},
error : function(jqXHR, textStatus, errorThrown) {
jQueryloader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
// Run load_posts() on document load
jQuery(document).ready(function(){
load_posts();
});
// Run load_posts() on scroll
jQuery(document).on('scroll', function() {
var distanceFromBottom = Math.floor(jQuery(document).height() - jQuery(document).scrollTop() - jQuery(window).height());
if(distanceFromBottom < 400) {
load_posts();
}
});
// AJAX Load More Function (in functions.php)
function load_more(){
$cat = $_REQUEST['cat'];
$page = $_POST['pageNumber'];
header("Content-Type: text/html");
$args = array(
'cat' => $cat,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'suppress_filters' => true,
'posts_per_page' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
locate_template('/parts/news-loop.php', TRUE, FALSE);
endwhile; else :
echo "No More Posts";
endif;
wp_reset_postdata();
die();
}
add_action('wp_ajax_nopriv_load_more', 'load_more');
add_action('wp_ajax_load_more', 'load_more');
// The loop template
<?php
$cats = get_the_category();
$cat_slug = $cats[0]->slug;
?>
<div class="news-post">
<h2><?php the_title(); ?> - <?php the_time('dS F Y') ;?></h2>
<div class="news-line"></div>
<div class="news-hex <?php echo $cat_slug; ?>"></div>
<div class="text">
<p><?php echo wp_trim_words(get_the_content(), 40, '...') ?></p>
<a class="more" href="<?php the_permalink(); ?>">FIND OUT MORE</a>
</div>
<div class="clear"></div>
</div>