setup_postdata( WP_Post|object|int $post )

Set up global post data.


Description Description


Parameters Parameters

$post

(WP_Post|object|int) (Required) WP_Post instance or Post ID/object.


Top ↑

Return Return

(bool) True when finished.


Top ↑

Source Source

File: wp-includes/query.php

function setup_postdata( $post ) {
	global $wp_query;

	if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
		return $wp_query->setup_postdata( $post );
	}

	return false;
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Added the ability to pass a post ID to $post.
1.5.0 Introduced.

Top ↑

More Information More Information

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.

Top ↑

Usage Usage


<?php 
global $post;

// modify the $post variable with the post data you want. Note that this variable must have this name!

setup_postdata( $post ); 
?>

 

 



Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by mslade

    An important note about setup_postdata and the $post global: setup_postdata( $new_post ) sets various globals related to the current post but it does not update the $post global. This disjoint can cause problems both in WP internals and in plugins/themes.

    Therefore if you call setup_postdata( $new_post ), you should also assign it to the global $post object.

  2. Skip to note 2 content
    Contributed by Codex

    Example 2

    <ul>
    <?php
    global $wpdb, $post;
    
    $str    = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'";
    $result = $wpdb->get_results( $str );
    
    if ( $result ) {
    	foreach ( $result as $post ):
    		setup_postdata( $post );
    		?>
    		<li><a href="<?php the_permalink()?>"><?php the_title();?></a></li>
    		<?php 
    	endforeach;
    }
    ?>
    </ul>
    
  3. Skip to note 3 content
    Contributed by Codex

    Example 1

    <ul>
    	<?php
    	global $post;
    	
    	$myposts = get_posts( array(
    		'posts_per_page' => 5,
    		'offset'         => 1,
    		'category'       => 1
    	) );
    	
    	if ( $myposts ) :
    		foreach ( $myposts as $post ) :
    		  setup_postdata( $post ); ?>
    			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    		endforeach; 
    		wp_reset_postdata();
    	endif;
    	?>
    </ul>
    

You must log in before being able to contribute a note or feedback.