Display post list within category list sorted by name [duplicate]

EDIT:

Well, it seems the following approach is a bit DB consuming. Pieter Goosen posted a very interesting alternative. Since this approach has already been accepted as a correct answer I don’t know, it it is possible to mark this question still as a duplicate. I flagged my answer so a moderator might have a look. Thanks.


I first collect all data in an multidimensional array. The subarrays are the categories.

So, I first load all categories with get_categories(). They are ordered by title. I load all of them into $post_categories while the array key is the ID of the category. The category information like the name will be stored in $post_categories[ category_id ]['cat'].

After this I run the query, but I make sure, it is ordered by title. Now, I get all the categories the post is attached to and I save the post in $post_categories[ category_id ]['posts'].

Now I have an multidimensional Array, which I just output with two foreach() loops.

$args = array( 
        'type' => 'projetos' 
    );
    $all_categories = get_categories( $args );
    $post_categories = array();
    foreach( $all_categories as $category )
        $post_categories[ $category->term_id ]['cat'] = $category;
    $args = array(
        'post_type' => 'projetos',
        'orderby' => 'title',
        'order' => 'asc' 
    );
    $my_query = new WP_Query( $args );
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()){ 
            $my_query->the_post();
            $p = array();
            $p['permalink'] = get_the_permalink();
            $p['title'] = get_the_title();
            foreach( get_the_category() as $category )
                $post_categories[ $category->term_id ]['posts'][] = $p;
        }
    }

    foreach( $post_categories as $cat ){
        if( ! isset( $cat['posts'] ) || count( $cat['posts'] ) == 0 )
            continue;
        ?>
        <strong><?php echo $cat['cat']->name; ?></strong><br />
        <?php 
        foreach( $cat['posts'] as $post ): 

        ?>
        <a href="https://wordpress.stackexchange.com/questions/184313/<?php echo $post["permalink']; ?>"><?php echo $post['title']; ?></a><br />
        <?php endforeach;
    }

    wp_reset_query();