admin管理员组

文章数量:1252691

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;
endforeach; 

Please can you explain?

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;
endforeach; 

Please can you explain?

Share Improve this question asked May 15, 2013 at 19:34 user28566user28566
Add a comment  | 

1 Answer 1

Reset to default 21

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

The main variable among these is $post, which holds the post object itself.

In your example it's not explicit, but what is happening is that your loop assigns data to $post. If its name wasn't $post, you would need to name it explicitly (global $post; $post = $some_other_post;).

However, there are a bunch of other globals and the purpose of setup_postdata() is to fill them with data. If you look at the source, these 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.

本文标签: What does setuppostdata (post ) do