Reputation: 575
AJAX load more returns the same posts every time. Issue is in WP_Query because this code works when I remove it. I can't figure it out what is wrong with my WP_Query.
This is part of index.php
$category_id = get_cat_ID('Događaji');
$exlude_latest_featured_post = array($featuredID);
$args = array(
'category__not_in' => array($category_id),
'post__not_in' => $exlude_latest_featured_post,
'posts_per_page' => 10,
);
$main_loop = new WP_Query ( $args );
while ($main_loop->have_posts()) : $main_loop->the_post(); ?>
<?php get_template_part('loop/content'); ?>
<?php endwhile; ?>
<div class="listing-more-posts">
<a>
<?php
$link_label = '<img class="listing-more-posts-image" src="'. get_bloginfo('template_directory') .'/images/more-posts-2.gif" alt="Učitaj još postova">';
next_posts_link($link_label);
?>
</a>
</div>
This is my loadmore.js file. As I said, it works fine when I remove WP_Query in index.php
jQuery(function($){
// Ajax (next) page load
var pageLoading = false;
function loadContent($link){
if( pageLoading == true ){
return;
}
pageLoading = true;
$.ajax({
type: "get",
url: $link.attr("href"),
dataType: "html",
success: function(response){
var html = $('<div>').html(response);
// 'standard' blog layout
var $articles = $(html).find("#post-listing article");
//$("#main").append(articles);
$link.closest(".listing-more-posts").before($articles);
// remove old nav wrapper (new one is added with new content)
// if( $link != null ){
$link.closest(".listing-more-posts").html($(html).find(".listing-more-posts").html());
// }
pageLoading = false;
}
});
}
$("body").on("click", ".listing-more-posts a", function(e){
e.preventDefault();
console.log("click");
// var $link = $(this);
$(this).parent().addClass('loading');
loadContent($(this));
});
});
I was searching for answer but couldn't find it. From the answers I found so far I think I need to do something with tracking page number, but I am not sure how to do that.
Thank you
Upvotes: 0
Views: 1605
Reputation: 575
I got it.
I was breaking main loop by doing things from above. I countinued to search and after some time I found one really useful action hook called per_get_posts and that was solution for my problem
This hook is called after the query variable object is created, but before the actual query is run.
- Wordpress Codex
All what I had to do now was this two things:
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$category_id = get_cat_ID('Događaji');
$query->set( 'category__not_in', array($category_id) );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
//Exclude latest featured post from showing in loop
function exclude_latest_post( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$exlude_latest_featured_post = array($featuredID);
$query->set( 'post__not_in', $exlude_latest_featured_post );
}
}
add_action( 'pre_get_posts', 'exclude_latest_post' );
Upvotes: 1