Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

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
share|improve this answer
    
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 Sep 4 '13 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. –  Jacob Raccuia Sep 4 '13 at 18:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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