Home » Functions » setup_postdata

The "setup_postdata" function in WordPress is used to set up the global post data for the current post in the loop. It allows you to access various information and properties of the post easily within the loop, such as the post ID, title, content, author, and more.

When you call the "setup_postdata" function, it sets up the global $post variable with the data of the current post in the loop. This makes it convenient to use functions like "the_title" or "the_content" without passing any parameters.

Example Usage:

// The Query
$the_query = new WP_Query( 'category_name=featured&posts_per_page=1' );

// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        setup_postdata( $post );

        // Display post title
        echo '<h2>' . get_the_title() . '</h2>';

        // Display post content
} else {
    // no posts found
/* Restore original Post Data */

In the example above, we start by initializing a new query for posts with the category "featured" and limiting the number of posts to 1. Then, we enter the loop and call the "setup_postdata" function, passing the current post as the parameter. This sets up the global $post variable. We can then easily access the post title using "get_the_title" and the post content using "the_content".

Finally, after the loop, we use the "wp_reset_postdata" function to restore the original post data.

Overall, the "setup_postdata" function simplifies the process of accessing post data within the loop, making it easier to display information from the current post.

Learn More on

Register an account to save your snippets or go Pro to get more features.