Paginate custom $wp_query in admin end

I’ve taken information in an admin page (can be a menu_page or a submenu_page) using WP_Query(). Made a table to display the information also. Made a pagination too. But appears that, the pagination is not working. While searching for solution, found that, Christine Cooper got stuck in a similar problem in her end, but good part is, she made a solution taking suggestion from Milo. That solution was nice, and that solved my problem too. But some final touches were required, so I made my code working and presenting here for you. You can make it more nicer.

What actually is happening, and why?

Not being a copy-paste programmer, a good programmer should always ask for the base. So, what we’ve learned is, there’s no $wp_query object is loading in our page. So Query argument is not adding up into the URL. That’s why the popular pagination conditional:

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

is not actually working here, because get_query_var() isn’t actually getting anything. That’s why we are bound to use $_GET to fetch the $paged parameter, as Milo taught us.

Now we’re setting up some basic pagination markup:

$nextpage = $paged + 1;

and, for previous pages, we made:

$prevpage = max( ($paged - 1), 0 );

Easy as pie! Next page, so we added 1, and previous page, so we deducted 1. But to put things in positive values, we’re using PHP function max().

So, let’s assume our query is like below:

We’re passing the per page value set from Setting > Reading as our posts_per_page parameter. So we’ve put this into our function to not to query further. You can pass your custom value, if you’ve any, using $posts_per_page = 5. We’re taking the default posts_per_page as a fallback if the $items_per_page is empty. Note that, we are using $_GET method instead of get_query_var() in $paged.

So here’s our pagination function:

And, we can use it like below:

Now we can send our own parameters. And moreover, we can see in which page we in now, there’s a next page, previous page, last page and first page button too. We can now use our pagination with more ease.

Pagination for custom admin page $wp-query

Pagination for custom admin page $wp-query

So, as we’re informed now, we can use. Please report if there’s any bug. And if you like, or if it helps you don’t forget to comment here. And don’t hesitate to share and spread what just helped you.

Mayeenul Islam
Front End Designer & WordPress Developer

_____________________________

Courtesy

Thanks to Christine Cooper and Milo for there suggestion and code snippet^, on which we’ve made our more furnished copy of the snippet.

Comment here...