0

I use the code below, added to a template, to display random posts.

<ul>
<?php $posts = get_posts('orderby=rand&numberposts=5'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } ?>
</ul>

Do I need to reset, presumably by changing

<?php } ?>

to

<?php } wp_reset_postdata(); ?>

And does the need to reset depend on whether this code-block is before or after other loops/queries in the template?

1 Answer 1

1

wp_reset_postdata()

wp_reset_postdata() will restores the global $post variable to the current post in the main query. This is useful when using WP_Query to customize loops or create multiple loops on the same page.

This Answer will solve all your queries about wp_reset_postdata() & WP_Query & get_posts

1
  • Accept the answer if it helped you. Commented May 19, 2017 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.