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.

5 comments:

  1. Thanks for the post!

    I need help getting the WP_Query loop working with pagination. Here's my problem: If you go to my site, www.usedboatmall.com, you will see a custom search widget in the sidebar. The search works properly on the first page, but once you go the next page it does not pass the custom search query along.

    For example, if you search for Bass Boat you get 14 results (as of this morning). The first 10 results are displayed on the first page. If you click to page 2 it shows 0 results.

    Is this something you can help me with?

    ReplyDelete
  2. You have now completely removed wp-pagenavi from your website! Can you post the parameters in the get_template_part function (path/to/theme/category.php)?

    ReplyDelete
  3. Not working for me. Pagination disappears after adding 'paged' function. Been working on this for 2 days, any help would be appreciated.

    ReplyDelete
  4. thenk you. worked

    ReplyDelete

About Me

Web Developer From Dhaka, Bangladesh.