Codex tools: Log in
Contents |
Set up global post data. Helps to format custom query results for using Template tags.
<?php
global $post;
setup_postdata( $post );
?>
Important: You must make use the global $post variable to pass the post details into this function, otherwise functions like the_title() don't work properly...
Example...
global $post; // Assign your post details to $post (& not any other variable name!!!!) $post = $post_object; setup_postdata( $post ); ...
This will not work...
global $post; setup_postdata( $post_object );
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; global $post; $str = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'"; $result = $wpdb->get_results($str); 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.