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

The codex defines it as 'Set up global post data. Helps to format custom query results for using Template tags.' I don't really understand this.

Here is a code example :

global $post;
$args = array( 'numberposts' => -1);
$posts = get_posts($args);
foreach( $posts as $post) : setup_postdata($post);
echo $post->ID;

Please can you explain?

share|improve this question
up vote 9 down vote accepted

Template tag functions rely on global variables to access post being processed and retrieve data from it or related to it.

Main variable of them is $post which holds post object itself. In your example it's not explicit, but what is happening is that your loop assigns data to $post, if name for iteration wasn't $post you would need to do that explicitly (global $post; $post = $some_other_post;).

However there is bunch of other globals and purpose of setup_postdata() is to fill them in with data. If you look at source namely they are:

global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;

Note that in most cases you should be calling wp_reset_postdata() afterwards to return globals to their original state.

share|improve this answer
Thank-you that makes perfect sense! – mattnewbie May 15 '13 at 19:52

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.