WordPress Get Custom Query Work With wp_pagenavi

Hi Friends,  Wordpress providing lots of functions and options for developers to work, But sometime we got some situation in which we have to write custom wordpress query. So if we use custom query then we have to take care of pagination and paging variables too. So in this article I will explain that If you are going to use custom query then how you can use wp_pagenavi function(to use wp_pagenavi you have to install WP-Pagenavi plugin).

So below is code which is useful for custom query work with wp_pagenavi :

<?php
//Custom Query
$wp_custom_query = new WP_Query('cat=-3&paged=' . $paged);
//Start While loop
while ($wp_custom_query->have_posts()) : $wp_custom_query->the_post(); ?>
<h2 class="title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
 <!-- Other Stuffs will come here -->
<?php
endwhile;
if(function_exists('wp_pagenavi')) {
 wp_pagenavi( array(
 'query' =>$wp_custom_query
 ));
}
?>

Now explanation of above code step by step :
Line 3 : It is custom query which is excluding category which have id 3 and then added $paged variable, Remember “&paged=' . $paged” is important part and without it pagination will not work.
Line 5 : while loop starts.
Line 6 : Print post title and assign it link.
Line 10 to 14 : These lines check that ‘wp_pagenavi’ function exists or not, in case you dont installed Wp-PageNavi plugin then it will not give error. Now if ‘wp_pagenavi’ exists then call ‘wp_pagenavi’ function and then pass ‘$wp_custom_query’ in it, So pagination will work for custom query.

I hope it helps someone. If you know any other method to acheive this then post it in comment, I will add it here under your name.

I am wordpress DeveloperWordPress Developer India and WordPress Freelancer. If you have any projects related to wordpress or PHP you can contact me.

No Comments

Leave a Reply