How to create a custom loop in WordPress

posted on by - 3015 views

In the WordPress world, we use the word loop to talk about post lists, those beautiful content flows we can see in basically every blog or magazine. It’s WordPress that normally takes care of them: for example, if we’re reading the homepage (the index.php) we should see the posts in inverse chronological order, from the newest to the oldest; in the same way, in archive pages (i.e.: archive.php, category.php, tag.php), we still should see posts in inverse chronological order, but filtered by categories, or tags, or whatever the archive type is.

Great. So, those are default loops, which means that WordPress is the one who’s taking care of it all. But the real question now is…

How to create a custom loop in WordPress?

With the powerful tools offered by WordPress we can create a custom loop. Which means, we can create custom lists of posts based on… whatever we want. We can decide how many posts to show, include or exclude categories or tags, authors, custom meta keys, post types, and so on. We can do that by using a class called WP_Query().

So, now: let’s create a custom query that will show the last three posts published on our website. Let’s start easy.

The first thing we have to do is to go wherever we want our custom loop to appear, and to create the arguments of our query, so we can specify what we want to see in our list.

$args = array( 
    'posts_per_page' => 3, 
    'post_type' => 'post', 
    'post_status' => 'publish' 

Okay, so here we’re basically telling WordPress that we want to show three posts that are already been published on our website. Now we can use the class WP_Query() to create the list.

$my_custom_query = new WP_Query( $args );

…and now, let’s go on with the canonical structure of a loop (check this out).

if( $my_custom_query->have_posts() ){
    while( $my_custom_query->have_posts() ){
        // HTML structure of our post
} else {
    // Error message: sorry, no posts here

That’s it. Now our custom loop is created and will show exactly the posts that we want to show. Of course, we still have to fill our HTML structure, using WordPress functions like the_title(), the_permalink() and so on (use the WordPress Codex to learn how to use all those).

At the end of everything, and after our first if condition, it’s crucial to remember to reset the query, so can WordPress can go back to its normal loops.


Now it’s really all done.

Remember that you can fill your query arguments with so many parameters. I suggest to check out this awesome post from Bill Erickson to have a complete list of them.