Skip to content

What is the Loop?

15 Aug 2010 (Updated: 9 Jan 2012) • no comments Code, Wordpress

WordPress code

WordPress Code

When you first start getting beyond using plugins and into editing files in WordPress, you will often see a reference to add some code within the loop.

For quite a while, this threw me because often articles are written for experienced users without taking beginners into consideration (something I try to avoid), so they will tell you to put the code in the loop, without ever telling you what the loop is.

Well, the loop is simply a portion of your theme files that display the main content on each page. A loop is a computing term where a process is repeated until some parameter is met and it ends. In WordPress, it’s usually a case of querying the database for posts or comments that meet a certain set of criteria and then ends when 10 (or another predefined number) have been returned. The loop will be noticeable because it always starts and ends with a specific piece of code.

The start of the loop is typically identified by an if and while statement. E.g.:

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

And the end of the loop is typically identified by an endwhile and endif statement.

<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

So, the loop is everything between these two lines of code. These lines will appear on template files such as index.php, single.php and archive.php. If you are trying to add code to the loop it is because you are trying to add functionality to the way posts are displayed and what is displayed in them. So you will need some PHP and CSS knowledge to know where to put the code and how to apply it appropriately so that you achieve the desired result. There’s always help on offer over at the WordPress Forums, but honestly, the best way to learn (rather than just have someone help you fix an immediate problem) is by experimenting. You might not want to do this on an important live site, but if you do, just be sure to backup everything first!

Related posts:

  1. How To Display Code Within A WordPress Post
  2. Watching the BBC iPlayer outside of the UK, safely and reliably
  3. 10 WordPress plugins that every website needs… and others that may come in handy
  4. Using Anchors in WordPress
  5. Automate WordPress Database Backups for Care-Free Protection
mojo themes

About the Author

Dave Clements designs awesome websites and offers WordPress consulting services in his spare time, along with eating Wheat Thins, spending time with friends and family, watching Indie films and playing with his array of Apple products.

Like it? Share it!

Comments

There are no comments on this entry.

Add a Comment

Name - Required

Email - Required

Website - Optional

CommentLuv badge