WordPress 3.1 and setup_postdata

After upgrading one of my websites to WordPress to version 3.1, the loops that contained setup_postdata() created a mess. After some testing, I realised that setup_postdata() will only return the correct data if the argument passed is $post, i.e. setup_postdata($post). I had used setup_postdata( $ancestor ) instead and it created a mess after the upgrade.

Now I had this running in my code:

foreach( $ancestors as $ancestor )  {
   setup_postdata( $ancestor );
   // Do things with the_title()
   // Do things with the_post_thumbnail()
   // Do things with the_permalink()
   // Do things with get_post_custom()
   // Do alot of other things with $ancestor
}

I could solve this mess by changing to the below code, but this required changing all $ancestor variables to $post

foreach( $ancestors as $post )  {
   setup_postdata( $post );
   // Do things with the_title()
   // Do things with the_post_thumbnail()
   // Do things with the_permalink()
   // Do things with get_post_custom()
   // Do alot of other things with $post 
}

But I reckoned it wasn’t as efficient, and also it might create more bugs due to the edit of so many variable calls. In the end I opted for a quick fix to pass $ancestor into the $post variable just before setup_postdata( $post ). In this way, I’ll still able to get the correct data from the_title(), the_post_thumbnail(), the_permalink() and get_post_custom(), without having to change all $ancestor calls to $post that come after.

foreach( $ancestors as $ancestor )  {
   $post = $ancestor;
   setup_postdata( $post );
   // Do things with the_title()
   // Do things with the_post_thumbnail()
   // Do things with the_permalink()
   // Do things with get_post_custom()
   // Do alot of other things with $ancestor
}

Ok, hope this might be useful if you faced the same issue. Anyone has alternative solutions?

Leave a Comment