WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to switch WordPress's post context, sort of like switch_to_blog() but for posts. What's the safest way to alter WordPress's global state and switch it back?

share|improve this question
up vote 2 down vote accepted

Use setup_postdata() to change and wp_reset_postdata() to roll back to original.

share|improve this answer
Very helpful, thanks Rarst. I don't need to loop through any posts. Just get a single one via get_post( $post_id ). Is this still the way to go given that background? I'm not using have_post(), the_post() and the like, just get_post(). (Googlers, see also: codex.wordpress.org/Class_Reference/…) – editor Jun 29 '11 at 16:57
@editor yep, same principle. The point of setup_postdata() is that it doesn't care about the Loop or more precisely it's one of small standalone cogs in it. – Rarst Jun 29 '11 at 17:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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