Why should i use wp_reset_postdata()?

WordPress uses global $post variable. This way you don’t have to pass post nor post_ID as param for functions. So you can call the_title() and WP knows which title should it show.

This behavior works fine, if there is only one loop on the site. But if you create your own custom loops and iterate them, then you modify the global $post variable…

Let’s look at some sample. Let’s say this is single.php for article “News 01”:

    ...
    while ( have_posts() ) : the_post();
?>
    <h1><?php the_title(); // it will show News 01 ?></h1>
    <?php the_content(); // it will show its content ?>

    <?php
        $related = new WP_Query( ... );
        while ( $related->have_posts() ) : $related->the_post();
    ?>
        <article>
            <h2><?php the_title(); // it will show other title ?></h2>
        </article>
    <?php endwhile; ?>

    <?php the_category(); // what will that show? categories for which post? ?>

In the last line, it will show categories for last of related posts. Why? Because this is the post that global $post variable is set to.

But if you call wp_reset_postdata(); after endwhile, then you’ll set global $post back to the post from global $wp_query object, so everything will work fine again.

Leave a Comment

tech