Jasjit Singh Marwah Jasjit Singh Marwah - 1 month ago 7
Ajax Question

Wordpress: Custom WP_Query returning first page posts for all 'paged' parameter values

I'm trying to create a "load more posts" button for my Wordpress blog page using AJAX. The Javascript function that takes care of passing the 'paged', 'offset' and 'posts_per_page' parameters is doing so successfully (I've checked a hundred times!).

The offset and posts_per_page parameters work fine (I repeatedly changed their values to test this) but the WP_Query always returns the posts on the front page, even though the value of $page changes each time more posts are loaded.

Just incase the $paged value was getting messed up somewhere, I used static numbers for the 'paged' parameter but it still only shows first page posts no matter what the value.

Everything executes fine and I receive no error message, with debugging enabled. The posts do load - just not the right ones.

Other info: my own theme, no plugins running right now.

The code below is from a function in my functions.php file.

$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'desc',
'posts_per_page' => $ppp,
'paged' => $page,
'offset' => $offset, //I've tried simply putting 3, 5 etc
);

$loop = new WP_Query($args);

if ($loop -> have_posts()) :
while ($loop -> have_posts()) : $loop -> the_post();
the_title();
endwhile;
endif;
wp_reset_postdata();


I've only entered what I believe to be relevant code, in order to make it easier to read. Let me know if you'd like me to add something. And thank you!

EDIT: Using the query() function directly makes it work but I really don't want to mess with the main query object...and this just means that everything else in my code is fine. WP_Query is just being weird.

Answer

You can't used offset and paged together - you would only use one or the other. Using them together breaks pagination. If you want the posts that would appear on page 2 (assuming you have 10 to a page), use either:

'paged' => 2

or

'offset' => 10