Custom query pagination with PageNavi plugin in WordPress

Sometimes you want show your post in a specific way, ordering with some special feature(custom field) or anything. In this post, I explain how show your posts in your own order using PageNavi plugin to paginate the list of posts. You can use the same steps to use other paginator plugin or your own paginator.

Sometimes you can’t create your own order to show the posts using query_posts, so you can’t use wordpress loop. If you creates your own loop, then PageNavi plugin doesn’t work because it uses wordpress loop.

In this case, this is a solution to do your own order and to use PageNavi plugin:

The first step is create our own SQL sentence to obtain the posts and execute it using wpdb object. In this query we obtain the posts in our custom order. In this sentence we must use the values of pagination and post per page.

//get the actual page
$paged = get_query_var('paged');

//get the amount of posts per page

//create the custom query
$query="SELECT *,meta_value AS code_year FROM wp_posts,wp_postmeta WHERE post_type='my-custom-post' AND post_status='publish' AND post_id=ID AND meta_key='year' ORDER BY code_year DESC LIMIT $post_per_page OFFSET ".$paged*$post_per_page;

//execute query and get the posts

If the query discard some posts that default wordpress shows, then we must configure the default query to obtain the same amount of posts. If we don’t do this, then the PageNavi paginator can show more or less pages in the paginator.

//set the default query


Then we create an own loop and we add the paginator.

//creates a loop
foreach($myPosts as $p){
 // something...

//creates paginator

That’s all!

Do you need some help?

Let's get started. Tell us a little about yourself and your organization
and we can start a conversation about your needs and our capabilities.

Related Posts