The WordPress Loop Explained

Get a free WP Checkup Today!
Get a completely free health check of your WordPress site, no email or signup required.

The WordPress loop is big. It’s huge. It’s critical. Without it, your WordPress site won’t work.

By this, I don’t mean that it’s large. In fact, it should be as lean, tight and quick as possible. But it’s a major part of what makes WordPress, well, WordPress. Without it you can’t query the database and display your content, whether that’s your blog archive, your “About” page or your latest post.

Nothing works without the WordPress Loop.

So, now we’ve established how important the loop is, you might be wondering just what it is if you haven’t come across it before.

In this post, I’ll answer that question. I’ll show you what the loop is, how it works and where it should go. I’ll also give you some tips for customizing the WordPress loop and making it work for you.

Let’s start by identifying what the WordPress loop does and where it goes.

What is the WordPress Loop and Where Do I Find It?

The WordPress Loop is a few (or sometimes many) lines of code that access the database, fetch any relevant content and then display it. The code will include PHP for accessing the database and a mix of PHP and HTML for outputting what’s found.

The reason it’s called the loop is because it loops – it repeats itself until there’s nothing else to display. When viewing a static page this means it’ll just loop once but on a category archive or your main blog page, it’ll keep on looping and outputting content until there’s nothing left to display.

What the WordPress loop fetches and outputs depends on a few things:

  • What kind of content is being viewed
  • Any customizations you’ve made to the WordPress Loop (more of which later)
  • The functions you use to display items from the database (such as the post title, content, and any metadata)
  • The HTML you wrap your content in.

You’ll find the WordPress Loop in every template file in your theme. In this post, we’ll examine the WordPress Loop in the current default theme, twenty sixteen. If you don’t already have access to that theme, download it and open it up in your favourite code editor. As we work through this post I’ll make reference to different files and chunks of code in that theme and it helps if you can take a look and follow along.

In this post, I'll take apart the loop in the Twenty Sixteen default theme.
In this post, I’ll take apart the loop in the Twenty Sixteen default theme.

Where’s the WordPress Loop? Finding it in Template Files

You’ll find the WordPress Loop in every theme template file, or you may find a function that pulls it in from a template part instead.

A template part is a file containing code that’s used repeatedly throughout the theme, of which the WordPress Loop is an example. So instead of repeating the loop in every single template file, each file pulls in the template part and runs the same code.

You can use more than one include file in your theme so, for example, you might want just one version of the WordPress Loop for all archive pages and another for all single pages.

Let’s take a look at the Twenty Sixteen theme to make sense of all this.

Here’s the file structure of the theme:

The file structure of the twenty sixteen theme

There are a bunch of template files:

  • 404.php
  • archive.php
  • footer.php
  • image.php
  • index.php
  • page.php
  • search.php
  • single.php

The theme also has some template parts in the main folder:

  • comments.php
  • footer.php
  • header.php
  • searchform.php
  • sidebar-content-bottom.php
  • sidebar.php

And it has more template parts inside the template-parts folder. Each of these will be called somewhere else in the theme. Other files such as functions.php and style.css have their own specific role.

Let’s take a look at an example of the WordPress Loop. Firstly, open the page.php file.

Here’s its code, in full:

So which part of this is the loop?

Well. there’s one thing you need to look out for when looking for the loop, and that’s this line:

This is what starts the WordPress Loop. And this line closes the loop:

So this means that the loop in this page.php template file is running using these lines of code:

But this doesn’t include the template tags and HTML that displays the contents of the WordPress Loop. Instead, that’s all contained in the content-page.php file. It does it with this line:

That get_template_part() function fetches the contents of the template part and runs them at this point in the template file, just as if the code was coded into this file.

Before we move on to looking at the contents of that template part in detail, take some time to open some other template files in the theme. Each of them references the relevant template part, with a few exceptions:

  • 404.php doesn’t include a WordPress Loop because if a user lands on a 404 page there won’t be any data to fetch and output.
  • archive.php and index.php fetch the template part for the relevant post format, using the post format taxonomy. This means that you can write a template part for each post format, with the code needed to output posts of different formats. If these files don’t exist it will fall back to content.php.
  • image.php doesn’t fetch a template part – instead the loop is coded within the template file.
  • page.php fetches the content-page.php template part.
  • search.php fetches the content-search.php template part.
  • single.php fetches the content-single.php template part.

THEMES

Stunning drag ’n’ drop themes with Upfront

Drag, scale, position, customize and see every edit you make to your website – in real-time – with our Upfront theme framework for WordPress. Choose from our collection of starter themes and get started customizing your site right away. You know that design you’ve got in your head? You can build it with Upfront.

TRY UPFRONT FREE LEARN MORE

The WordPress Loop Dissected

Let’s move on to take a closer look at the WordPress Loop. As we’ve already been working with page.php, let’s examine the content-page.php file. Open that in your code editor.

Note: If you’re writing a theme, you can choose to use template parts for your loop or code it directly into the template files. Using a term,plate part will make your theme more efficient but you may find that the theme you’re using just has the loop coded into the template file. Both will work.

Here’s the code in content-page.php:

Let’s step through each section of this one at a time.

Opening the Element and Displaying a Header

First, the file opens an article element and outputs the post title inside a header element:

The article element has an ID that uses the the_ID() template tag to fetch the ID of the post, and a class that’s defined using the post_class() template tag. This gives it a class that includes the ID of the post, the post type, taxonomies and more.

A header element is then opened, which includes the post title using the the_title() template tag. This has parameters for the markup that precedes and follows the post title – so it’s contained in a h1 element with the entry-title class.

The header element is then closed.

Displaying Metadata

The next step is to display any metadata. In this theme, there isn’t much of this – just the post thumbnail. This is displayed using the twentysixteen_post_thumbnail() function, which is specific to this theme. If you want to find out how this function works, take a look in the theme’s functions.php file – in the current version this function is defined from line 398.

In some themes, more metadata will be output here, such as any custom fields, author information and more. If you want to add this to your own themes, check out our tutorial on working with metadata.

Outputting the Post Content

Now the WordPress Loop will output the post’s content, with these lines:

Let’s take a look at what this does.

  1. Firstly, it opens a div with the entry-content class.
  2. Then it uses the the_content() template tag to fetch the content for the database and display it.
  3. It uses the wp_link_pages() template tag to display links to earlier and later posts for paginated posts. In this template part this won’t do anything as pages aren’t paginated, but in a single post it’ll display a link to the previous and next posts.
  4. It closes the entry-content div.

In some template files or template parts the content won’t be output, but the excerpt will instead. If you have a loop in your archive.php file you’ll probably choose to use the_excerpt() instead of the_content() to output the excerpt instead.

Finishing Things Off

The twenty sixteen theme then has a link that a logged user with the relevant user role can click on to edit the post:

This uses the edit_post_link() function with a few parameters that define exactly what’s output.

In some themes you’ll find that more metadata is output here.

Finally, the article element that contains everything is closed.

Customizing the WordPress Loop

So that’s the standard WordPress Loop. This will automatically fetch the appropriate content from the database, depending on what page is being viewed, and output it. It’s incredibly efficient, because the same code is used to display lots of different types of content, from posts to pages and other post types, as well as archives for posts, categories, authors and more.

If you don’t want the WordPress Loop to work in the standard way for each type of content, you can amend it. Or if you want to output a completely different loop (or an extra loop) on a page, you can do so. Let’s take a quick look at how you might do this.

Amending the Main Loop

Before you think about writing your own loop, try amending the main loop instead. This is much more efficient because you’re still using that main query that’s running on each page.

To do this, you write e function that you attach to the pre_get_posts hook. Inside this function you use a conditional tag to define when the query will be amended and some code to tell WordPress exactly how to amend it.

Let’s take a look at an example. The main blog page only includes posts of the post post type: it won’t show any of your custom post types. If you want to amend this to display a custom post type on your home page as well, you can.

Let’s say your custom post type is registered as myposttype. Here’s the function you would add to your theme’s functions.php file to add these to the main blog page:

This checks that we’re on the main blog page with is_home(), that we’re not in the admin screens with !is_admin() and that the main query is running with $query->is_main_query(). If all of these are the case, then it defines which two post types are output in the loop using $query->set('post_type', array( 'post', 'myposttype' ) ).

Writing a New Loop

If you want to display content on a page that wouldn’t be fetched by the main loop, or you want to run multiple loops on one page, then you can write your own new query and loop to do this.

There are three methods for doing this:

  • Use the get_posts() function to fetch and output posts, with your own parameters for the number of posts, the taxonomy terms or anything else you want to focus own.
  • Use the get_pages() function to do the same for pages.
  • Use the WP_Query class to fetch and output absolutely anything you want. This is an extremely flexible and useful class that you can use wherever you want in your theme.

For guidance on using each of these, see our guide to writing custom queries.

Understanding the WordPress Loop will Help You Create Better WordPress Themes

Hopefully, you’ve now got a better understanding of the WordPress loop and how it works.

Knowing what the WordPress Loop consists of will help you to make more sense of the code in the themes that you use on your site. It’s also essential if you’re going to write your own themes: it’s much better to understand the WordPress Loop and write your own than it is to just copy one from elsewhere. This will make your theme do exactly what you need it to do with no wasted code, improving efficiency.

It’s a crucial part of any theme and now you understand it, that will significantly boost your theme building skills.

If you have any questions about using or coding the WordPress Loop, let me know in the comments below! VIEW 3 comments
Get a free WP Checkup Today!
Get a completely free health check of your WordPress site, no email or signup required.