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

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

Do I need to reset, presumably by changing

<?php } ?>


<?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?



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

  • Accept the answer if it helped you. – JItendra Rana May 19 '17 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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