12/08/2018, 15:05

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

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, fetch only certain items from certain categories, only items not in certain categories, those published within a date range, or with other particular identifying information.

Every page template within a WordPress theme will likely contain 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, withhave_posts checking to ensure that there are, in fact, any posts to find. Then the loop happens – while there are still posts (again using have_posts), it iterates through the next post and calls up the_post – which refers to the one currently being iterated through.

Particular Queries

If your needs are more advanced than simply returning every post that there is on your website, you’ll need to limit your queries. This is where WP_Query comes into play.

Filtering by Category

In the below example, modified from an example in the Codex, we will query for posts that are in the category which has the id of 4. Then, you can see a sample of the contents of the loop itself. Here, we check for posts with a category ID of 4, then, within the .post div, we display the post’s title (linked to the post), the date of the post, the post’s content, and the post’s metadata.

 
<?php $query = new WP_Query( array( 'cat' => 4 ) ); ?>

 
<?php if ( $query->have_posts() ) {
      while ( $query->have_posts() ) {
        $query->the_post(); ?>
        <div class="post">
             
            <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

             
            <small><?php the_time( 'F jS, Y' ); ?> by <?php the_author_posts_link(); ?></small>

                          
            <div class="entry">
                  <?php the_content(); ?>
            </div>

                         
            <p class="postmetadata"><?php _e( 'Posted in' ); ?> <?php the_category( ', ' ); ?></p>
        </div> 
    }
}

The use of WP_Query can lead to some very customizable results. You can include posts of only one category, or several, or include all except for those from one category or another. You can search and return posts that contain a keyword, or locate posts by ID, use the post_type to show only data from pages, and more. If you want to learn in more depth about WP_Query, take a look at the WP_Query documentation.

Tip: You can get the ID number of a category in several ways. One easy way is to head over to “Posts”, then “Categories” in your WP-Admin. Right click on the desired category name in the list, and save the URL. Then paste it in a text editor or notepad somewhere and take a look. As an example, it might look something like this: http://example.com/wp-admin/term.php?taxonomy=category&tag_ID=4&post_type=post&wp_http_referer=%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dcategory – you’re looking for the tag_ID number!

Filtering by Custom Field Values

The custom fields that are available in WordPress can be fantastically useful, and you may at times also need to filter posts by the values set in those as well. A simple task, but it’s worth showing for beginning WordPress developers (or those who haven’t delved far into custom templates or The Loop) to realize how customizable all of this is. Say that you have a custom field department and you’re looking for posts with the value marketing:

$query = new WP_Query( array('meta_key' => 'department', 'meta_value' => 'marketing') );

.

Understanding “The Loop”

The truely best way to understand The Loop is simply to use it. Use it to fetch your content in the templates you create for themes, or in the code that you customize in existing templates in existing themes. When you want to do something, filter for certain criteria, run The Loop again – check the The Loop documentation in the Codex, or hit up Google for ideas. The sky’s the limit!

https://www.sitepoint.com/understanding-loop-wordpress/ Author: https://www.sitepoint.com/author/jeffsmith/

0