Tuesday, April 5, 2011

[SOLVED] WP-PageNavi, wp_pagenavi for custom query

WP-Pagenavi is a great plugin for paginating your WordPress Pages. Many people find it not working for custom queries like

get_posts, query_posts or for WP_Query. Today we'll solve the mystery.

Previously I edited the plugin to work for the custom queries but now the latest version has a built in feature to add your custom query object.

Suppose we make a custom query for getting some specific posts. The post ids are 1,5,8,9,10,34

$my_query = new WP_Query(
 array(
 'post_in' =>array(1,5,8,9,10,34)
 )

);

//If the total page number > 1 we will show the pagination

if($my_query->max_num_pages>1)
if(function_exists('wp_pagenavi'))
wp_pagenavi(array(
   'query' =>$my_query   
   ));

//note how  $my_query has been passed to wp_pagenavi  



You should set your posts_per_page to lower than the total page number to see the pagination. You should see the Pagination now but Wait Sailor, We are not done Yet!

You see that when you click on the second page you actually see the contents from the first page. So the solution is here.

Check your WordPress version before trying the solution


//Revised code to show posts from all pages

// page no from query

$paged = get_query_var ('paged'); 


// pass the paged value to the WP_Query

$my_query = new WP_Query( array(
 'post__in'  =>  array(1,5,8,9,10,34) ,
 'paged' => $paged
 
) );


//If the total page number > 1 we will show the pagination

if($my_query->max_num_pages>1)
if(function_exists('wp_pagenavi'))
wp_pagenavi(array(
   'query' =>$my_query   
   ));

//note how  $my_query has been passed to wp_pagenavi  



And you can use wp_pagenavi for get_posts,query_posts providing a paged value. If you're having any problem implementing, you can post your problem here. I will try to solve your problem.

About Me

Web Developer From Dhaka, Bangladesh.