Codex

Function Reference/setup postdata

Contents

Description

Set up global post data. Helps to format custom query results for using Template tags.

Usage

<?php 
global $post;
setup_postdata$post ); 
?>

Parameters

$post
(object) (required) A post object.
Default: None

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

Return Values

This function always returns true.

Example 1

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

Example 2

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

Change Log

Source File

setup_postdata() is located in wp-includes/query.php.

Related

See also index of Function Reference and index of Template Tags.