The next example is a carbon copy of the previous loop example, only with several key (X)HTML elements added for clarity. Copy & paste this code into the index.php 1 of your WordPress theme and examine the results in a browser. Hopefully, combining the code comments with the browser output 2 will give you a crystal clear picture of the various features of the WordPress loop.

// any code included here occurs before the wordpress loop and is always displayed
<h1>This text is generated via the h1 element included before the WordPress loop.</h1>
<p>Any code included in this part of the document is processed only once.</p>

<?php if (have_posts()) : ?>

	// if there are posts to display, process any code included here only once
	// display any code output from this region above the entire set of posts
	<h2>This text is generated via the h2 element only if there are posts.</h2>
	<p>Any code included in this part of the document is processed only once.</p>

	<?php while (have_posts()) : the_post(); ?>

		// loop through posts and process each according to the code specified here
		// process any code included in this region before the content of each post
		<h3><a href="<?php the_permalink() ?>">Title: <?php the_title(); ?></a></h3>
		<p>The title of this post is generated before the content of each post.</p>

		<?php the_content(); ?>  // this function displays the content of each post

		// process any code included in this region after the content of each post
		<h4>This is post #<?php the_ID(); ?>, written by <?php the_author(); ?></h4>
		<p>The previous metadata is generated after the content of each post.</p>

	<?php endwhile; ?>

	// stop the post loop and process any code included here only once
	// any code output will be displayed below the entire set of posts
	<h5>This text is generated via the h5 element only if there are posts.</h5>
	<p>Any code included in this part of the document is processed only once.</p>
	
<?php else : ?>

	// if there are no posts to display, process any code that is included here
	// the output of any code included here will be displayed instead of posts
	<p>If you are seeing this message, there are no posts to process/display.</p>
	<p>Any code included in this part of the document is processed only once.</p>

<?php endif; ?>

// any code included here occurs after the wordpress loop and is always displayed
<h6>This text is generated via the h6 element included after the WordPress loop.</h6>
<p>Any code included in this part of the document is processed only once.</p>
Tagged: