Show all custom post type posts sorted by custom taxonomy then by another custom taxonomy

First get a list of categories and a list of locations. Then loop through each category. Within each category loop through the list of locations and query posts that have the current category and the current location and output the list:

$categories = get_terms( array(
    'taxonomy' => 'shop_category',
) );

$locations = get_terms( array(
    'taxonomy' => 'shop_location',
) );

foreach ( $categories as $category ) {
    echo '<div class="box-category">' . $category->name . '</div>';

    foreach ( $locations as $location ) {
        $shops = new WP_Query( array(
            'post_type' => 'shop',
            'tax_query' => array(
                array(
                    'terms'    => $category->term_id,
                    'taxonomy' => 'shop_category',
                ),
                array(
                    'terms'    => $location->term_id,
                    'taxonomy' => 'shop_location',
                ),
            ),
        ) );

        if( $shops->have_posts() ) {
            echo '<div class="box-location">' . $location->name . '</div>';

            while ( $shops->have_posts() ) : $shops->the_post();
                echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a><br>';
            endwhile;
        }

        wp_reset_postdata();
    }
}

Leave a Comment