I was reading this post: When should you use WP_Query vs query_posts() vs get_posts()?, which seems to have become the go-to post for understanding the difference between the different functions for making custom loops.

In the article, it says that

[get_posts] doesn't modify global variables and is safe to use anywhere

Nonetheless, when I inserted into within another loop (I wanted to have a home page showing 3 columns, 2 done with custom fields, one with latest blog posts), I had to preserve the original $post, like so:

<?php global $post; // required
$tmp_post = $post; // save original post
args = array('numberposts' => 2); // Retrieve just 2 posts
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);
    //My posts code here (removed to simplify)
$post = $tmp_post; //go back to original post

Before I saved the original post, my third column, with the custom field, was blank, but after resetting, as above, it works fine.

Did I misunderstand what that line in the post meant? Did I do something I wasn't supposed to?

1 Answer 1


get_posts doesn't modify global variables & is safe to use anywhere but setup_postdata does modify the global variables.

Use the function wp_reset_postdata() just after the foreach loop. It reverses the changes made by setup_postdata. The thing it does is basically same as you did in your example, you just won't need to worry about the temporary variable.

  • I tried removing setup_postdata from my foreach, but I get the same problem. I still had to reset the post... Which also makes me wonder, what's the point of setup_postdata in the first place (nothing seemed to change after I deleted it)? I had it there because all the code examples I saw had it.
    – coopersita
    Oct 25, 2012 at 17:56
  • setup_postdata does only one thing, which is setting the global post data (this allows you to use template functions like the_title()). If you don't want to use them, you don't need setup_postdata. get_posts doesn't change anything, it probably is something else. Oct 25, 2012 at 18:04
  • Here's the link to the codex codex.wordpress.org/Function_Reference/setup_postdata Oct 25, 2012 at 18:05
  • You're right! I found the culprit, as usual, it was a plugin: Advanced Custom Fields. Thanks.
    – coopersita
    Oct 25, 2012 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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