WP_Query pagination not working in admin area

I’ve created a custom plugin page. On this page, I list posts using wp_query(). It works fine. I want to add pagination, but it doesn’t work, even when I’m using the code provided within codex:

<?php
// set the "paged" parameter 
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

// the query
$the_query = new WP_Query( 'posts_per_page=2&paged=' . $paged ); 

if ( $the_query->have_posts() ) :

// the loop
while ( $the_query->have_posts() ) : $the_query->the_post(); 

the_title(); 
endwhile;

// next_posts_link() usage with max_num_pages
next_posts_link( 'Older Entries', $the_query->max_num_pages );
previous_posts_link( 'Newer Entries' );

// clean up after the query and pagination
wp_reset_postdata(); 

else:  
echo 'Sorry, no posts matched your criteria.';
endif; ?>

When clicking on the pagination link, it loads up new page with the same posts. Why is this not working in the wp-admin area?

1 Answer
1

Milo noted that there is no $wp_query object in wp-admin page, so we can get $paged via:

$paged = ( $_GET['paged'] ) ? $_GET['paged'] : 1;

Now that we have $paged, we can code our own pagination. I will demonstrate how in its very simplest form.

First let’s get maximum pagination pages:

$max_pages = $the_query->max_num_pages;

Then calculate the next page:

$nextpage = $paged + 1;

Finally, let’s create our pagination link. We do a basic if statement checking if $max_pages is greater than $paged:

if ($max_pages > $paged) {
    echo '<a href="admin.php?page=plugin-page.php&paged='. $nextpage .'">Load More Topics</a>';
}

It is as simple as that.

Update

To enable previous page you can simply add:

$prevpage = max( ($paged - 1), 0 ); //max() will discard any negative value
if ($prevpage !== 0) {
   echo '<a href="admin.php?page=plugin-page.php&paged='. $prevpage .'">Previous page</a>';
}

Leave a Comment