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');
if($paged>0)
 $paged--;

//get the amount of posts per page
$post_per_page=get_option('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
$myPosts=$wpdb->get_results($query,OBJECT);

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

query_posts(array('post_type'=>'my-custom-post'));

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


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

//creates paginator
if($wp_query->max_num_pages>1){
 wp_pagenavi();
}

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