I'm trying to filter results of an AJAX infinite scroll feature/Load More button on a Wordpress posts page.
If I hard code in the Category ID as an argument for WP_Query
, it works, however I don't seem to be able to find a way to get the current collection of post's category ID.
Here's my load_more php function:
// Load More
add_action( 'wp_ajax_nopriv_load_more', 'load_more');
add_action( 'wp_ajax_load_more', 'load_more');
function load_more() {
$paged = $_POST["page"]+1;
$current_category = $wp_query->get_queried_object();
$query = new WP_Query( array(
'post' => 'post',
'paged' => $paged,
'cat' => $current_category
));
while ($query->have_posts()) : $query->the_post();
?>
<article class="post-box" id="content">
<div class="post-img-box">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/blank.png" alt="<?php the_title(); ?>" />
<?php } ?>
</div>
<h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
<?php the_excerpt(); ?>
<p class="post-date"><?php the_time('F j, Y'); ?></p>
</article>
<?php endwhile;
wp_reset_postdata();
die();
}
It's the $current_category = $wp_query->get_queried_object();
that isn't right/working.
I managed to solve it in a roundabout way:
1) Add $cat_id = get_query_var('cat');
to the top of the wordpress theme page. (index.php in my case).
2) Add data-category="<?php echo esc_attr($cat_id); ?>"
to the Load More html button tag.
3) In the jQuery .ajax request add the data-category
to the data request object:
$(document).on('click', '.load-more-btn', function() {
event.preventDefault();
var that = $(this);
var page = that.data('page');
var newPage = page+1;
var ajaxurl = that.data('url');
var cat = that.data('category');
console.log(page);
$.ajax({
url : ajaxurl,
type : 'post',
data : {
cat : cat,
page : page,
action : 'load_more'
},
error: function(response) {
console.log(reponse);
},
success : function(response) {
that.data('page', newPage);
$('.more-posts').append(response);
}
});
})
4) Add $current_category = $_POST['cat'];
to the php load_more()
function.
I was implementing onScroll infinite post loads on homepage and archive pages. I did it simply as below:
Localize current category ID
$data = array(
'processor' => get_template_directory_uri() . '/loopHandler.php',
'category' => get_query_var('cat'),
'loader' => get_template_directory_uri() . '/img/ajax-loader.gif');
wp_localize_script('ajaxLoop', 'localized_data', $data);
Post the category ID to query_posts
data: {numPosts : 1, pageNumber: page, category: localized_data.category },
Build query args
$posts = query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $_GET['category']
));