Atadj
Atadj

Reputation: 7200

WordPress - restore original WP_Query

I've got post type called "Portfolio" and single-portfolio.php file to handle it (it's WordPress). When I use there something like that it works like expected:

$post_id = $post->ID; //returns ID of current portfolio post. Good!

BUT when I post short query like this in the middle:

$post_id = $post->ID; //returns ID of current portfolio post. Good!
wp_reset_query();
query_posts('posts_per_page=4');
    if ( have_posts() ) : while ( have_posts() ) : the_post();
            the_id(); //returns ID of standard blog post
        endwhile;
    endif; 
wp_reset_query();
$post_id = $post->ID; //returns ID of last BLOG post. Wrong!

I'm only concerned about $post_id variable in above example. I want it to always return correct ID of current PORTFOLIO post and not be dependent on other queries. How do I achieve that?

Upvotes: 0

Views: 1799

Answers (2)

Astrotim
Astrotim

Reputation: 2172

I believe wp_reset_postdata() will give you the result you are looking for.

$the_query = new WP_Query( 'posts_per_page=4' );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        // output
    endwhile;
endif;

wp_reset_postdata();

I should note that there is another approach which I have documented in another question asking about what is the difference and when each should be used.

Upvotes: 4

hakre
hakre

Reputation: 198194

The wp_reset_query function does reset the global $post variable as well, but only based on the global $wp_query variable. That still is modified, probably due to one of the little flaws in Wordpress. In your case I'd say a simple WP_Query::rewind_posts() should do it:

wp_reset_query();
$wp_query->rewind_posts();
$post_id = $post->ID;

Also you should consider to create a second loop, not overwrite the first one.

See as well:

Upvotes: 0

Related Questions