The WordPress loop

Basic loop

The WordPress loop is used to grab the content of a post or group of posts and display it on the front end of a site. A simple loop is shown below.

The first line uses an “if” statement to check to see if there are any posts. The ternary operator ” : ” is used to separate the next statement, in this case a “while” loop. The while loop, loops through each post and displays the same information for each post. An else statement triggers if no posts are present, displaying a message.

The loop can also display a single post or page.

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

	........code to loop

<?php endwhile; else: ?>

Sorry, no posts to list

<?php endif; ?>

The code inside the loop changes depending on whether it is a list of posts or a single post

Blog list

To see a list of posts, use the following code. Inside the loop, the title, thumbnail and excerpt are retrieved from the database, using built in WordPress functions.

 


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

<h2><?php the_title() ;?></h2>

	<?php the_post_thumbnail(); ?>
	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

Sorry, no posts to list
<?php endif; ?>

Single post

For a single post the title and content are shown.

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

<h1><?php the_title() ;?></h1>

	<?php the_content(); ?>

<?php endwhile; else: ?>

Sorry, this page does not exist

<?php endif; ?>

What can be displayed in the loop?

There are many built in functions that can be used in the loop.

Leave a Reply

Your email address will not be published. Required fields are marked *