LESSON 04 / 04

The Loop

The Loop prints posts: while there are posts, set up the next one and use template tags like the_title and the_permalink. Custom loops show any posts anywhere.

๐ŸŽ“Mediumlevel
โฑ๏ธ35 minto finish
โœ๏ธ1activities

๐Ÿ“‚ How Themes Work๐Ÿท๏ธ WordPress

๐ŸŽฏ By the end of this lesson you canโ€ฆ

  • Write the standard Loop
  • Use common template tags inside it
  • Write a custom query with get_posts or WP_Query
๐Ÿ”Œ WordPress PHP index.php ๐Ÿ‘† Tap a line to explain it
1<?php2// WordPress normally prepares the posts for you. Our mini WordPress has three demo posts.3if ( have_posts() ) :4    while ( have_posts() ) : the_post();5        echo '<article>';6        echo '<h2><a href="'; the_permalink(); echo '">'; the_title(); echo "</a></h2>\n";7        echo '<small>' . get_the_date() . "</small>\n";8        the_excerpt();9        echo "</article>\n";10    endwhile;11else :12    echo '<p>No posts yet.</p>';13endif;
๐Ÿ”Œ WordPress PHP latest-posts.php ๐Ÿ‘† Tap a line to explain it
1<?php2$recent = get_posts( [ 'numberposts' => 2 ] );3echo "<h3>Latest</h3>\n<ul>\n";4foreach ( $recent as $p ) {5    echo '<li><a href="' . esc_url( get_permalink( $p ) ) . '">' . esc_html( get_the_title( $p ) ) . "</a></li>\n";6}7echo "</ul>\n";8wp_reset_postdata();
๐Ÿ› ๏ธ Title list

Using the Loop, print each demo postโ€™s title on its own line prefixed with its number: 1. Hello World etc. (Posts come newest first.)

๐Ÿ“Œ Key takeaways

  • while ( have_posts() ) : the_post(); โ€ฆ endwhile;
  • Inside the Loop: the_title(), the_permalink(), the_excerpt(), get_the_date().
  • After a custom loop, call wp_reset_postdata().

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.