Understanding “The Loop” in WordPress

When discussing WordPress, and specifically the development of themes (or creating new page templates inside an existing theme) you inevitably will run up against “The Loop”. The Loop is the framework within which WordPress constructs the content for any given page that user visits, whether that be a static home page or a blog view showcasing recent posts, or anything in between. It may sound a bit complex, but really, it’s just a looping mechanism.

The Loop, at its simplest, is a looping structure just like any other in programming. It iterates through what amounts to a list of all of your site’s content, cycling through your posts or pages, and fetching the requested content from them. At its most complicated, you can run The Loop multiple times in a page, fetching only certain parts of items from certain categories, or with particular identifying information.

Every page template within a WordPress theme will likely contain a copy of The Loop. It’s one way that the template can search for and acquire content from your pages and posts, which are stored in the database. Let’s take a look at some specifics:

A Basic Example of the Loop

<?php 
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        // Post Content here
    }
}
?>

You can see in the above example that it’s really a pretty straightforward setup. The entire thing starts with a conditional, with have_posts checking to ensure that there are, in fact, any posts to find. Then the loop – while there are still posts (again using have_posts), then call up the_post – the one currently being iterated through.

Continue reading %Understanding “The Loop” in WordPress%


Source: Sitepoint