Storing query variable and then using wp_reset_query

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.

Read More

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

Related posts

1 comment

  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
    

Comments are closed.