Should ‘setup_postdata()’ be reset with ‘wp_reset_postdata()’?

Starting with an example makes more sense, so here’s an example function:

function seo_meta_tags() {
    global $post;

    if( is_singular() ) {

        setup_postdata( $post );

        $description = str_replace( '... <a class="read-more" href="' . get_permalink() . '">Cont. reading &rarr;</a>', '...', get_the_excerpt() );

        wp_reset_postdata();

        echo '<meta itemprop="description" name="description" content="' . $description . '">';

    }
}

NOTE: The code is only to give you an idea of what I am trying to accomplish and not exactly how I am doing it.

Now coming to the point, should setup_postdata( $post ) be closed with wp_reset_postdata() as shown in the example?

1 Answer
1

As setup_postdata is messing with global variables that might be (most probably: are) used by other loops (including The Loop), you should always reset these variables to what they should be—according to the main query (i.e., what WordPress thinks the user wanted in the first place).
In addition, setup_postdata is provided with (a reference to) the $post global, which might be altered afterwards.

So, yes, setup_postdata should be accompanied by wp_reset_postdata.

As you can see in the code, the reset_postdata function is, in fact, calling setup_postdata on the original $post object.

Leave a Comment