1

I want to use a pagination function with a custom posts query (to get posts from a specific category). My pagination function gets the query from global $wp_query;

So in the following code I have assigned the original $wp_query to a temporary variable and after the query I assigned back. Finally I used wp_reset_query() function to reset the query.

So my question is that does it make any sense to store the original $wp_query first and then assign it back and then reset the query? If we are resetting the query, then isn't it unnecessary? I'm asking the question because I did read about this approach in an article, and I am not sure about this.

$temp_query = $wp_query; //#1. store original wp_query
$args = array(
    'cat' => 15,
    'paged' => $paged
);  
$wp_query = new WP_Query( $args );

while ( $wp_query -> have_posts() ) : $wp_query -> the_post();

endwhile;

my_pagination();    //call function

$wp_query = $temp_query;    //#2. assign back original wp_query

wp_reset_query();   //#3. reset query

1 Answer 1

2

wp_reset_query(); resets the query to the original main query of the page.

Therefore, storing the query in another variable is redundant and unnecessary.

Updated code:

$args = array(
    'cat' => 15,
    'paged' => $paged
);  
$custom_query = new WP_Query( $args );

while ($custom_query -> have_posts()) : $custom_query -> the_post();
endwhile;

my_pagination();    //call function
wp_reset_query();   //#3. reset query
2
  • Thanks for your answer. I'd normally use same as this, but as I said above the problem comes when I make the custom query. For example using above code, the while loop will get correct number of posts from that specific category, but the the pagination function will count all posts in blog, so if I use specific variable $wp_query, then it will work fine. May be it is because in the pagination function I has global wp_query. I have copied pagination function from here, see 'Basic example' codex.wordpress.org/Function_Reference/paginate_links
    – jay
    Commented Sep 4, 2013 at 18:07
  • 1
    So your pagination is getting messed up? Your question doesn't really state that. Do you call global $wp_query; inside your pagination? Maybe try making that global $custom_query;. It's hard to say since your pagination code isn't here either. Commented Sep 4, 2013 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.