๐ฏ 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.