Languages: English • postdata 日本語 (Add your language)
Sets up global post data. Helps to format custom query results for using Template tags.
setup_postdata() fills the global variables $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages, which help many Template Tags work in the current post context.
setup_postdata() does not assign the global $post variable so it's important that you do this yourself. Failure to do so will cause problems with any hooks that use any of the above globals in conjunction with the $post global, as they will refer to separate entities.
<?php
global $post;
setup_postdata( $post );
?>
You must pass a reference to the global $post variable, otherwise functions like the_title() don't work properly.
For example:
global $post; // Assign your post details to $post (& not any other variable name!!!!) $post = $post_object; setup_postdata( $post ); // ...
A "clever" formulation:
setup_postdata( $GLOBALS['post'] =& $post_object );
This will not work:
global $post; setup_postdata( $post_object ); // oops
This function always returns true.
<ul> <?php global $post; $args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; wp_reset_postdata(); ?> </ul>
<ul> <?php global $wpdb,$post; $result = $wpdb->get_results("SELECT $wpdb->posts.* FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'"); foreach($result as $post): setup_postdata($post);?> <li><a href="<?php the_permalink()?>"><?php the_title();?></a></li><?php endforeach;?> </ul>
setup_postdata() is located in wp-includes/query.php
.