If you are a WordPress theme developer, a programmer, or just an overall enthusiast eager to learn what a WordPress loop is, this article is for you! Without further ado, let us start with the basics: What is a loop?
The WordPress loop is a PHP code that shows WordPress posts or simply put; it is used in various themes to display posts on any given web page. Not only that it runs on most pages you see, but it also allows you to modify and customize it to your liking.
These website loops can be used to maybe list post by comment count, show posts with images, and so on.
When you look at the loop, you can see that some functions run by default in order to show posts. Theme developers can use those functions and template tags to customize how each post in the loop is shown.
Those template tags work only inside the WordPress default loop, and it is used to format, arrange and publish post data.
WordPress loop is without a doubt the most crucial part of the WordPress code, and let us dive deep into how your website loops.
WordPress page loop for beginners
As we already mentioned, the post loop is a code that outputs all of the information WordPress has about a post or posts. It runs in the background through each post, and it finds the database one by one, which allows it to supply information about all found posts.
Here is an example of how WordPress loop through posts works:
- you start the loop,
- take action with each found post or page,
- close the loop.
These three steps represent the basic logic behind the loop. From this point, you can get creative and filter the posts you found by using the query. The query tells the loop what we are looking for. In our example, it would look like this:
- define what we are looking for,
- start the loop,
- take action with each found posts or page,
- close the loop.
If you have experience with PHP code, you might be familiar with “while” function that is used in loops to run through the database query and dynamically display the information without having to enter every single database row manually.
WordPress while loop works the same way.
Example of a standard WordPress loop
Below is an example of a standard WordPress loop that can be used on any page.
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post() ?>
// Post display here
<?php endwhile ?>
<?php else : ?>
// Content if there are no posts to show
<?php endif ?>
Take a look at have_posts() and the_post() functions. The first one determines if there are any posts to show, and the second one sets up data and internal pointes which helps the have_posts() function.
If there is nothing to show, then the function should display a message informing the users.
If there are the posts we are looking for, then the loop will display them one by one.
Here, have a block of code that will actually show posts, it’s on us!
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post() ?>
<div <?php post_class() ?>>
<h2><a href='<?php the_permalink() ?>'><?php the_title() ?></a></h2>
<div class='post-excerpt'>
<?php the_excerpt() ?>
</div>
<div class='post-meta'>
<time><?php the_time( 'Y-m-d' ) ?></time>
<?php if ( has_category() ) : ?>
<span class='post-categories'><?php the_category( ', ' ) ?></span>
<?php endif ?>
</div>
</div>
<?php endwhile ?>
<?php else : ?>
<h2>There are no posts here</h2>
<p>Do you want to go back to the <a href='<?php echo site_url() ?>'>home page?
<?php endif ?>
The content shown here is determined by the query which we already talked about, and how that content is shown depends on the loop. This amount of customization is awesome and it is what makes WordPress stand out.
Great job! Now you know what is a post loop!
Using code to change the main query
Before we begin, we have to warn you that changing the main query can have unintended consequences if you do not know what you are doing. Take caution while experimenting!
We have to look at the hooks if we want to modify core functionality. The hooks enable us to change text length, change the login screen, re-phrase error messages, change custom post types, and so much more.
add_action( 'pre_get_posts', 'my_exclude_category' );
function my_exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-92' );
}
}
Note that we use the pre_get_post hook to modify the parameter of the main query before it runs. The code above does the same thing as the one before, but this time it excludes category 92 from our home page. Hence, the main query is modified
Have a look at the is_home() and is_main_query() functions. They are here to make sure that the query is only modified on the home page and if it is the main query.
Here’s another code that can be useful in a WordPress blog loop.
Let’s say that an author on your website has plagiarized some (or all) of his content, and you want to remove all of his or her posts permanently, or until the problem is resolved.
That can be done by adding a code like this:
add_action( 'pre_get_posts', 'my_exclude_author' );
function my_exclude_author( $query ) {
$query->set( 'author', '-23' );
}
With this conditional function you remove the author’s post from both your website and your backend. You can find all of the conditional tags in the WordPress Codex. Here’s what the last code should look like in the end:
add_action( 'pre_get_posts', 'my_exclude_author' );
function my_exclude_author( $query ) {
if( !is_admin() ) {
$query->set( 'author', '-23' );
}
}
Table of Contents
FAQ on the WordPress loop
What’s the WordPress loop, anyway?
Oh man, this takes me back! So, at its core, the WordPress loop is the engine of WP that displays content from the database on your site.
It’s the heart of many WP templates and tells the system which posts or pages to show and in what order. Think of it as the DJ of your WordPress party, picking out the right tunes (or posts) for your guests.
Why’s the loop so essential in theme development?
Ah, theme development, a fun puzzle every time! The loop is like the backbone of a WordPress theme. Without it, your theme would be a silent movie with no plot.
It fetches the content based on WP_Query parameters, and through template tags, you can customize what and how the content is displayed. Ever heard of themes with special styles for certain posts? Yeah, that’s the loop’s magic at work.
How does the WP_Query relate to the loop?
Alright, dive in with me here. WP_Query is the class that defines and fetches the content. The loop then goes through the results WP_Query returns.
Think of WP_Query as the chef that prepares the dishes, while the loop serves them to your guests. And with custom post types and taxonomies, this chef can whip up an impressive range of dishes!
What’s the difference between have_posts() and the_post()?
Classic question! have_posts() checks if there are posts left in the query to loop through. It’s like asking, “Hey, any more songs on that playlist?”
Meanwhile, the_post() sets up the current post, so you’re ready to display its details. It’s akin to hitting play on the next track. Both are super crucial in the dance of the loop.
How can I customize what posts show up in the loop?
Ah, the power of customization! To change which posts appear, you tweak the WP_Query parameters or use pre_get_posts filter.
Whether it’s a category loop, tag loop, or any other custom query, there’s so much you can do. Want to show posts from a certain category? Or maybe sort them by a custom field? The world’s your oyster!
Can I have multiple loops in one page?
You betcha! Multiple loops are a thing, especially when you want different sections, like a main article list followed by a sidebar with recent posts.
You just need to reset the loop with wp_reset_postdata()
after each custom WP_Query. And with template parts, it’s even more organized. Just remember not to overdo it – no one likes a cluttered party!
What are conditional tags in the context of the loop?
So, conditional tags are the gatekeepers of the loop. They let you control where and when certain content displays.
You might use them to show a piece of content only on single posts, or perhaps only in a certain taxonomy. They’re like the bouncers of your WP club, deciding who gets in based on the guest list.
How do I add pagination to the loop?
Ah, pagination, the art of not overwhelming your visitors! By using pagination functions, you can break up your posts into multiple pages.
Instead of showing a never-ending list of posts, give your users a breather. Functions like paginate_links()
or the classic “next and previous” links help here. Because, let’s be real, no one wants to scroll forever.
Why would I ever need to modify the main query?
Good one! Sometimes, the default settings just won’t cut it. Maybe you want your homepage to show only a specific custom post type or exclude certain categories.
By using the pre_get_posts action, you can tweak the main query without writing a new one. It’s like adjusting the main settings on your stereo for the perfect sound.
What happens if there’s an issue with my loop?
Oof, been there! If there’s a hiccup with the loop, your site might show no content, or even worse, throw errors. Always backup before tinkering. Check your WP_Query parameters and template hierarchy.
And if all else fails, the WordPress Codex and community forums are gold mines for troubleshooting. Remember, every developer faces a glitchy loop at least once. You got this!
Ending thoughts on WordPress loop
Using WordPress loop is a great way of customizing your posts, pages, or simply put – your website. The loop requires you to have a basic understanding of how WordPress works and code logic.
Unless you want to do a quick test, we would not recommend using query_posts() function. You can use various hooks in case you need to modify the original query. Always be cautious when changing the WordPress loop code.
We hope that this article was a good first step towards your WordPress loop mastery!
If you enjoyed this article about WordPress loop, you should also read these:
- 504 error in WordPress: How to fix it
- 12 Tips for Creating a Successful WordPress Premium Plugin or Theme
- How to Leverage Browser Caching in WordPress? Steps to Follow