Couple of issues here;
-
Don’t use
get_postsfor paginated queries. It legally breaks/ignore pagination as it passesno_found_rows=truetoWP_Query. Further more,get_postsonly returns the$postsproperty 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 forWP_Query`. -
Do not use the global
$postsvariable (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_postsor similar functions,setup_postdata()requires the use of the$postglobal. Here you need to remember to usewp_reset_postdata()after you are done to restore the$postglobal -
When using
get_posts, you don’t need the check for aWP_Errorobject asget_postsonly return an array of posts or an empty array. It will never return aWP_Errorobject
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