This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

WordPress Loop: The Mainstay of Your Content Display

Updated on September 4, 2023

7 Min Read

When it comes to showcasing your blog posts in your WordPress theme, there’s a fundamental piece of code that every WordPress user should be familiar with: the WordPress Loop, often referred to simply as “The Loop” in the WordPress Codex.

The WordPress Loop is not just another piece of code; it’s the backbone of your WordPress theme, the engine that drives the dynamic display of your blog posts on your website.

In this comprehensive guide, we’ll take you through the essentials of the WordPress Loop, complete with real-world examples, to ensure you grasp its inner workings, learn how to tailor it to your needs and discover exactly where it operates within your WordPress theme.

What Is WordPress Loop?

A PHP code that displays WordPress posts is called a loop or WordPress loop. WordPress themes use a loop to display the posts on the current web pages.

Loop is based on some functions designed to display the posts by running these functions. WordPress Loop is one of the most important elements of WordPress code, with several Template Tags that are used to publish, format, and arrange post data.

The Loop displays the following information by default for each post:

  • Title (the_title())
  • Time (the_time())
  • Categories (the_category()).

Streamline Your WordPress Development with Cloudways Managed Hosting!

Bypass the tedious setup processes and jump straight into coding. Create, innovate, and loop.

When Should You Use a Loop in WordPress?

You can use loops in WordPress whenever you want to display posts, pages, custom post types, or any content stored in the WordPress database.

Here are some possible scenarios where you should use a loop in WordPress:

  • Displaying blog posts
  • Displaying page templates
  • Displaying archives
  • Displaying search results
  • Displaying custom post types
  • Displaying a set number of posts per page

How to Add WordPress Loop

Here’s how you can add the WordPress loop using coding lines. The below-mentioned code is quite basic and might require customizations.

For now, let’s have a look at the basic code of the loop. Then we can go over each line to understand it.

//Check If posts exist, if yes then execute while loop

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

//Display Posts code here

           <h2><?php the_title() ;?></h2> //Display the title of the post

            <?php the_post_thumbnail(); ?> //Display the post thumbnail AKA featured image

            <?php the_excerpt(); ?> //Display excerpt of the post

<?php endwhile; else : ?> //End the while loop

                       <p><?php _e( 'No Posts To Display.' ); ?></p>

<?php endif; ?> //end If statement

Code Explanation

In the Loop, we have one “if” statement and a “while” loop. The “if” statement checks if there are posts available to be displayed, the “have_posts” WordPress function is a boolean one, that returns a true or false value. If there are posts found, it returns “true” and code proceeds to “while” loop.

The “while” loop also has the “have_posts” WordPress function. It returns “true” equal to the number of times we have set blog posts to be displayed in the WordPress admin.

The code then proceeds to the WordPress function “the_post”. This function sets up the post and then we can use more functions to extract elements from the posts. In the above-stated example we have used:

the_title -> fetches the post title

the_post_thumbnail -> fetches the featured image of the blog post

the_excerpt -> fetches the excerpt of the blog post

There are certainly more functions that we can use to extract elements from posts, we will cover a few examples.

Struggling with WordPress Loops?

With Cloudways’ Robust WordPress Hosting, you get hassle-free and powerful tools tailored for developers.

You have probably seen that blog post titles have links to the actual posts. Upon clicking on the hyperlink, you are navigated to a single-page view of the blog post. Most themes have a file called single.php; this file is called when you are viewing a single post.

We will use the “the_permalink” WordPress function and enclose the “the_title” function to link it.

Example:

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

           <h2><a href="<?php the_permalink(); ?>"><?php the_title() ;?></a></h2>

            <?php the_post_thumbnail(); ?>

            <?php the_excerpt(); ?>

<?php endwhile; else : ?> //End the while loop

             <p><?php _e( 'No Posts To Display.' ); ?></p>

<?php endif; ?>

How to Display the Content, Author, Date, and Category Using the Loop

You might have seen many blogs with posts that show the name of the author, the entire content of the main blog page, the date, and the category. You can easily display all these useful details within the loop using the following functions:

the_content – Displays the full blog content

then_author – Displays the author-name

the_time – Displays the time and date

the_category -Displays the category of the post

Your loop will look something like

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

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

           <?php the_author(); ?> <?php the_time('F j, Y'); ?> <?php the_category(); ?>

           <?php the_post_thumbnail(); ?>

           <?php the_content(); ?>

<?php endwhile; else : ?> //End the while loop

             <p><?php _e( 'No Posts To Display.' ); ?></p>

<?php endif; ?>

What Are Conditional Tags, and Why Should We Use Them?

Many tags are used to check for conditions, but fortunately, in WordPress, these are pretty much self-explanatory.

For example, “is_home” checks whether the current view is of the home page (main page of the blog). We can use Conditional Tags to initiate certain Loops.

For example, if we enclose our Loop between “if” condition that checks whether the current page is the main page, then the Loop will only be executed on the main page.

&lt;?php if (is_home()) {  //Returns true if current page is main/home page

&lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;

&lt;h2&gt;&lt;?php the_title() ;?&gt;&lt;/h2&gt;

&lt;?php the_post_thumbnail(); ?&gt;

&lt;?php the_excerpt(); ?&gt;

&lt;?php endwhile; else : ?&gt;

&lt;p&gt;&lt;?php _e( 'No Posts To Display.' ); ?&gt;&lt;/p&gt;

&lt;?php endif; ?&gt;

} ?&gt;

We can use Conditional Tags in our template files to control which Loop is executed, thus having multiple loops in a single file.

Some of the most used Conditional tags are.

is_admin() – Returns true when admin is logged in the site.

is_single() – Returns true if single post is being viewed.

is_page() – Returns true on certain pages, e.g. is_page(‘about-us’)

is_category() – Returns true on category pages, e.g. is_category(‘wordpress’)

is_tag() – Returns true on tags.

is_author() – Checks for author and Returns true. e.g. is_author(‘ahsan’)

is_404() – Returns true if the page does not exist, can be used on 404 pages to execute a customized Loop

has_excerpt() – Returns true if a post has an excerpt.

5 Useful Loops in WordPress

Let’s have a look at five common loops in WordPress.

1. Insert Ads After the First Post

If you need to place Ads after the first post, this is a way to do this.

<?php if (have_posts()) : ?>

<?php $count = 0; ?>

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

<?php $count++; ?>

<?php if ($count == 2) : ?>

//Paste your ad code here

<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php the_excerpt(); ?>

<?php else : ?>

<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php the_excerpt(); ?>

<?php endif; ?>

<?php endwhile; ?>

<?php endif; ?>

Just paste your Ad code and the ad will be placed after the first post.

2. Fetch Posts Between Two Dates

One of the common use cases is to fetch posts for a specific time period. To do so, use the WordPress loop like so.

<?php function filter_where($where = ’) {

$where .= " AND post_date >= '2009-03-17' AND post_date <= '2009-05-03'";

return $where;

}

add_filter('posts_where', 'filter_where');

query_posts($query_string);

while (have_posts()) :

the_post();

the_content();

endwhile;

?>

Inside the code, we use an SQL function that contains the WHERE clause. The function filter_where is then hooked to post_where() function.

3. List Upcoming Posts

A list of upcoming posts is a smart way of keeping the visitors busy on your blog. This can be achieved through the following loop.

<?php query_posts('showposts=10&post_status=future'); ?>

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

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

<span class="datetime"><?php the_time('j. F Y'); ?></span></p>

<?php endwhile;

else: ?><p>No future events scheduled.</p>

<?php endif; ?>

In the above code, we use the post_status function to fetch posts according to their published date.

4. Create An Archive Page

The archive page is a great way of listing your best posts from the past so that readers can still find them on your blog.

Make sure to create a template page to display archived posts.

<?php

/*

Template Name: Archives

*/

?>

<?php get_header(); ?>

<h2><?php $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");

if (0 < $numposts) $numposts = number_format($numposts); ?>

<h2><?php echo $numposts.' recipes published since October 06, 2008'; ?>

</h2>

<ul id="archive-list">

<?php

$myposts = get_posts('numberposts=-1&');

foreach($myposts as $post) : ?>

<li><?php the_time('m/d/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

<?php endforeach; ?>

</ul>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

5. Create Image Loop

The image loop is a great way of showing your blog posts in a gallery-like display. Each post is displayed with an image and its excerpt.

Let’s see how to do that using WordPress Loops.

function catch_that_image() {

global $post, $posts;

$first_img = ’;

ob_start();

ob_end_clean();

$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);

$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image

$first_img = "/images/default.jpg";

}

return $first_img;

}

To display the images on a browser, add the following code.

<?php

if (have_posts()) :

while (have_posts()) : the_post(); ?>

<a href="<?php the_permalink();?>" title="<?php the_title(); ?>" class="img-loop">

<img src="https://www.smashingmagazine.com/wp-content/uploads/images/wordpress-loop-hacks/<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" />

</a>

endwhile;

endif;

?>

WordPress have_posts function is used to check if any data is available to loop. It returns true if the data is available.

The Loop is the Future

Think of the Loop as the driving engine of WordPress themes. It is necessary to use it to display posts. This blog explains the basics of using a loop, but I recommend you go over the Loop in action to discover more ways of using it.

But, the Loop would work great if it is coupled with a high-performing fast WordPress hosting medium. Cloudways is ready for the Loop! Our tests have shown that websites on our WordPress hosting platform load 100% faster.

Q. What does loop do in WordPress?

WordPress Loop displays a list of data dynamically with specified parameters.

Q. What are the different types of loops in WordPress?

There are several types of loops; a user can create a loop as per his own requirements using the pre-defined WordPress functions.

Q. How to Display Any Number of Posts in a WordPress Loop?

To do so, you need to limit the number count while running the loop around WordPress posts.

Q. What Does Loop Display?

WordPress Loop can display data and images on a web page.

Q. What is the main loop in WordPress?

The main loop in WordPress is the core mechanism that queries the database for posts and then displays them on the page, typically in the order they were published.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Ahsan Parwez

Ahsan is the Community Team Manager at Cloudways. He loves to solve problems and help Cloudways' clients in any aspect he can. In his free time, you can find him playing RTS PC games.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now