Today I finally decided to dedicate a single tutorial on the wonderful WordPress loop. I will demonstrate how to create a basic loop and show several examples of the loop in action. The loop is what gets post and/or page data in WordPress template files, so if you ever have a need to make a custom page or post template, you’ll need to understand how the loop works.
The Basic WordPress Loop
Most often you will see the loop look something like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!————This is where you present your post data….————–>
<?php endwhile; else : ?>
<p><?php _e( ‘Sorry, no posts matched your criteria.’ ); ?></p>
<?php endif; ?>
The above example doesn’t contain the middle part of the loop in order to demonstrate where the loop typically begins and ends. That way you can find the loop in your current theme and work with it by knowing where it starts and stops at least. Next we’ll discuss what to put in between where it says <!————This is where you present your post data….————–>.
Fetching Data Inside a WordPress Loop
First I’ll show you how to display the Title as a link to the Post’s permalink.
<h2><a href=”<?php the_permalink(); ?>” rel=”bookmark” title=”Permanent Link to <?php the_title_attribute(); ?>”><?php the_title(); ?></a></h2>
Just place the above code example where it says you present your post data in the the loop example above.
You can display the Post’s content in a div with the following code inside of your loop:
<?php the_content(); ?>
Again, use the above code in between the starting and ending loop code explained above and this will display the general content of the post as entered into the standard WYSIWYG editor in the WordPress admin.
Using More Than One Loop
If you need to use two more more loops in the same template file, then you will have to reset the WordPress loop with rewind posts function like this:
<?php rewind_posts(); ?>
Just use the above line before your second loop and any loops afterwards and they will reset and be ready to function again.