Display multiple posts from each taxonomy

An image displaying a stack of papers

A lot of times I saw the question of how to display 2 or more posts from single category and stack them nicely in WordPress. The first thing that comes to mind is, of course is WP_Query.

Notice: This article was written in 2016. WordPress has changed a lot since then, so take this article with a grain of salt…

And true enough, we’ll need the query to get our posts. But WordPress default query class will only return posts, ordered in a certain way. Sadly, you cannot specify to query a specific amount of posts from each taxonomy. It would be a cool thing to have, and who knows, maybe we’ll have it somewhere in the future, but for now, we need to implement another way of doing this.

By no means is the technique I’ll show you here super advanced, but it takes some steps to execute properly.

In your page template, or archive, category, taxonomy or home page even, you’ll need to first fetch all the categories. You can fetch categories from custom post type, but here I’ll fetch just ordinary built in categories.

<?php

    $cat_args = array(
        'orderby'      => 'date',
        'order'        => 'DESC',
        'child_of'     => 0,
        'parent'       => '',
        'type'         => 'post',
        'hide_empty'   => true,
        'taxonomy'     => 'category',
    );

    $categories = get_categories( $cat_args );Code language: HTML, XML (xml)

Notice the taxonomy  parameter. You can change it to your custom taxonomy if you wish. Since get_categories() returns array of categories, we’ll create a foreach  loop and in that loop create our query. And that’s basically it. The whole thing looks like this:

<?php

    $cat_args = array(
        'orderby'      => 'date',
        'order'        => 'DESC',
        'child_of'     => 0,
        'parent'       => '',
        'type'         => 'post',
        'hide_empty'   => true,
        'taxonomy'     => 'category',
    );

    $categories = get_categories( $cat_args );

    foreach ( $categories as $category ) {

        $query_args = array(
            'post_type'      => 'post',
            'category_name'  => $category->slug,
            'posts_per_page' => 2,
            'orderby'        => 'date',
            'order'          => 'DESC'
        );

        $recent = new WP_Query($query_args);

        while( $recent->have_posts() ) :
            $recent->the_post();
        ?>
        <div class="element-item transition <?php echo $category->slug;?>" data-category="<?php echo $category->slug;?>">
            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                <div class="descrip">
                    <h2><?php the_title(); ?></h2>
                 </div>
            </a>
        </div>
        <?php endwhile;
    }
    wp_reset_postdata();
?>Code language: HTML, XML (xml)

Now you can create your own preferred layout, add more arguments to your query etc. It’s all up to you.

Granted this is not the most friendly piece of code because it runs queries inside foreach, so it’s like multiple queries withing queries within queries (queryseption? XD), but it’s all we can do for now. Plus we are only retrieving back 2 posts, so it’s not a taxing query to run.

The get_categories()  function can take other arguments, for instance

$args = array(
    'type'                     => 'post',
    'child_of'                 => 0,
    'parent'                   => '',
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'hide_empty'               => 1,
    'hierarchical'             => 1,
    'exclude'                  => '',
    'include'                  => '',
    'number'                   => '',
    'taxonomy'                 => 'category',
    'pad_counts'               => false
);Code language: PHP (php)

It’s up to you to sort them how you like. You can manipulate the resulting array using php if you wish, but I think you have all you need here.

That’s it for today, had to cut it a bit short and simple, have Swedish exam next week so I had to study for that, plus I have a plugin that I’m currently developing. I hope it will be out soon, so that I can put it here and on WP.org as well.

If you have any kind of questions feel free to leave them in the comments below, until next time, happy coding!

3 responses

  1. sonia maklouf Avatar
    sonia maklouf

    Denis when i read your tuto i ‘m wondering if there’s a way to get back argument of a wp_query.
    I mean for example if i had
    $query_args = array(
    ‘post_type’ => ‘post’,
    ‘category_name’ => $category->slug,
    ‘posts_per_page’ => 2,
    ‘orderby’ => ‘date’,
    ‘order’ => ‘DESC’
    );

    $recent = new WP_Query($query_args);
    and i need later in the code to get back the posts_per_page of $recent .
    Can i do $recent ->posts_per_page ?
    Is there a way to get from $recent its post type or any other of its arguments ?

    And thanks for your tutorials

    1. Well if you have set post_per page in your query, you know what it is, no? But if you want to use it later on, you could. It’s just an array, so you could get the arguments of it by specifying the key like $query_args['posts_per_page'] which will return 2 in our case. In the same way you could pull out the post type, or any other arguments that you’ve set up :)

      1. sonia maklouf Avatar
        sonia maklouf

        Thanks :-D

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.