Learn the WordPress Loop

  • Outputs posts through a theme’s template files.
  • Code in the loop will be executed for each post.
  • ex. <?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php endwhile; endif; ?>
  • Three Ways to Reset the Loop – Used when calling multiple loops, e.g., to display a list of posts as a table of contents and then display content further down.
    • rewind_posts() – For showing the same query in a different location on the same page.
    • wp_reset_postdata() – Most commonly used, restore global $post variable to the current post in the main query.
      • $secondary_query = new WP_Query( ‘category_name=example-category’ );if ( $secondary_query>have_posts() ) :
        echgo ‘<li>’ . get_the_title() . ‘</li>’;
        echo ‘</ul>’;
      • wp_reset_query() – Must be utilized if query_posts() is used in loop.
        • Calls wp_reset_post_data() when executed.
        • Best Practice: Use wp_reset_post_data() directly when working with custom loops and WP_Query.
        • Use of query_posts() is discouraged.