I'm executing a query inside of header.php which is apparently resetting the $post object so that all pages are getting the $post->ID of the last element in this loop.

$mypostsheader = get_posts(array('cat' => "$cat,-$catHidden",'numberposts' => $cb2_current_count));
$current_page = get_post( $current_page );?>
<div class="menu top">
    <ul><?php foreach($mypostsheader as $idx=>$post){
        if ( $post->ID == $current_page->ID )//do something; }

I've tried adding a rewind_posts() at the end of this function and also at the end of header.php but my echo $post->ID inside of page.php still returns the id of the last element in the query.

Any ideas?

  • You're already saving the current page in $current_page. Why not just set $post = $current_page; setup_postdata( $post ); after your loop? Or is there more to your question? – goldenapples Apr 6 '11 at 19:09
  • @goldenapples: good suggestion. I missed that. I actually got it to work using wp_reset_query() just before closing the function. I was previously trying to use rewind_posts() with no luck. – Scott B Apr 7 '11 at 18:16
  • @goldenapples: Your suggestion works. Please post it as an answer and I will upvote it and select it. Actually, I don't even have to call setup_postdata($post). I'm just resetting the post with $post = $current_page as per your suggestion. – Scott B Apr 7 '11 at 21:49

I found that one solution for this was to place a call to wp_reset_query() just before the close of the function call. I was trying to use rewind_posts() but it would not work. wp_reset_query() did the trick.

After doing that, thanks to @goldenapples excellent observation that I was already setting a pointer to the current $post object with my $current_page variable (duh!), I found that I could dump the wp_reset_query() call and instead just add this line in its place...

$post = $current_page;

The root cause is that I was resetting the $post object in the for loop (as $idx=>$post) and the query had to be reset so that the value of $post was a true reflection of the current $post object for the page in function calls below header.php

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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