Couple of issues here;
-
Don’t use
get_posts
for paginated queries. It legally breaks/ignore pagination as it passesno_found_rows=true
toWP_Query
. Further more,get_posts
only returns the$posts
property from the query object, and pagination needs other properties from the query object to calculate pagination. You can paginateget_posts
, but it is a really messy affair, and get_postsis just a wrapper function for
WP_Query`. -
Do not use the global
$posts
variable (or any other global variable in WordPress or PHP) as a custom variable. This breaks the global variables as you are assigning different content to the variable. This is the most likely issue that is causing the inconsistent results from your query withWP_Query
. Always use custom variables. The only exception to this is when you are usingsetup_postdata( $post )
withget_posts
or similar functions,setup_postdata()
requires the use of the$post
global. Here you need to remember to usewp_reset_postdata()
after you are done to restore the$post
global -
When using
get_posts
, you don’t need the check for aWP_Error
object asget_posts
only return an array of posts or an empty array. It will never return aWP_Error
object
You should try the following:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish',
'posts_per_page' => 5,
'paged' => $paged,
);
$q = new WP_Query( $args ),
if ( $q->have_posts() ) {
$displaylist="<div class="list-group">";
while ( $q->have_posts() ) {
$q->the_post();
// LOOP STUFF HERE
} // endwhile
$displaylist .= '</div>';
wp_pagenavi( array( 'query' => $q ) );
wp_reset_postdata(); // VERY VERY IMPORTANT
} // endif