What is the Loop?

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.:

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

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!

Leave a Reply