This is an article explaining the 3W1H of the well-known WordPress Loop(abbr. as the Loop).
Tbh, not all of the 5W1H is suitable in explaining tech terms. So I removed the Who and Where from it. 5W1H is generally a good tool and starting point in understanding something more thoroughly and deeply. So, let’s get started!
I’ll start with WHY first.
In general, the Loop is used to display multiple posts on a page. When you want to display an array of data in any specific order, you want to loop through that array intuitively.
Latest wordpress code at the time of writing is version 5.3.2.
Version of wordpress when
the_post() is introduced is 1.5.0. These two functions will be explained below.
WHAT and HOW
The Loop is a few lines of PHP code used to display posts. Core functions are
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <!-- Display post content here --> <!-- e.g. <?= the_title() ?> This displays the title of the current post. --> <!-- e.g. <?= the_content() ?> This displays the content of the current post. --> <?php endwhile; else : ?> <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?>
Iterate the post index in the loop, that is to update the global $post object as the current post. So that when you call
the_title() within the loop,
the_title() gets the title of the global $post object for you.
Also it sets up the post-related data in the global scope by calling
setup_postdata($post) (i.e. post id, post content or number of pages in the post, etc.), with $post being the global post object.
So where exactly and how do we use this piece of code?
I would like to pull in some quick wordpress basics here first. Whenever wordpress parses the user request, it follows the Template Hierarchy to find out which template file should be presented, and if no match is found, the theme’s
index.php file will be used. So very likely, you would find the Loop within every theme’s
In the default WordPress theme, there are template files for the index view, category view, and archive view, as well as a template for viewing individual posts. Each of these uses The Loop, but does so with slightly different formatting, as well as different uses of the template tags.https://codex.wordpress.org/The_Loop_in_Action#The_Loop_In_Other_Templates
In short, you can use the Loop in template files like
taxonomy.php, etc… Well the Loop is even found in
single.php in wordpress default twenty-something themes where you display a specific post. It seems unintuitive, but it is necessary, as
the_post() also sets up the post’s data and content in the global scope just as I have mentioned above. To be exact, you will find that
the_post() will call
generate_postdata() to populate the
global pages variable which contain the
post_content. Then in
global pages variable will be used to provide the content. You can test that yourself by removing the Loop and leaving the wrapped code behind, you’ll see.