Group WP_Query by category

You could look at modifying the WP_Query with a SQL command to group them, but that’s a bit beyond my current MySQL, however, I’ve always done it by running a foreach on the taxonomy itself with this http://codex.wordpress.org/Function_Reference/get_categories

Here’s some sample code:

<?php
    global $post;

    $current = get_the_ID($post->ID);
    $cargs = array(
        'child_of'      => 0,
        'orderby'       => 'name',
        'order'         => 'ASC',
        'hide_empty'    => 1,
        'taxonomy'      => 'category', //change this to any taxonomy
    );
    foreach (get_categories($cargs) as $tax) :
        // List posts by the terms for a custom taxonomy of any post type   
        $args = array(
            'post_type'         => 'post',
            'post_status'       => 'publish',
            'posts_per_page'    => -1,
            'orderby'           => 'title',
            'meta_key'          => '_rkv_issue_select',
            'meta_value'        => $current,
            'tax_query' => array(
                array(
                    'taxonomy'  => 'category',
                    'field'     => 'slug',
                    'terms'     => $tax->slug
                )
            )
        );
        if (get_posts($args)) :
    ?>
        <h2><?php echo $tax->name; ?></h2>
        <ul>
            <?php foreach(get_posts($args) as $p) : ?>
                <li><a href="https://wordpress.stackexchange.com/questions/37346/<?php echo get_permalink($p); ?>"><?php echo $p->post_title; ?></a></li>
            <?php endforeach; ?>
        </ul>
    <?php 
        endif;
    endforeach; 
?>

This will run through every category with posts (hide_empty is set to true) and does a get_posts on that (and also checks to make sure it has posts before outputting anything).

Wasn’t sure what you wanted for a header to separate the groupings so I used an h2 and added a link to the listing as well.

I changed it to get_posts because I’ve found it to be more efficient as it doesn’t override the global $post variable (less database calls, less use of wp_reset_query()).

Leave a Comment