Loop through posts of CatA and store value of CatB in separate array

So based in the information you’ve given me in the comments the following gist should work as you have described with your current setup.

https://gist.github.com/aj-adl/fab2cefd1450cbf24a5c

You provide it with a region, and it will get all posts from a region, loop through and build an array of producers, then do a subquery and loop for each producer.

It’s definitely not the most efficient way of doing it, and the main reason why we have to stuff around with everything is because WordPress doesn’t allow you to group by taxonomies.

If you changed the producers to being a meta value of a post, instead of a taxonomy, then you could do pretty much the same thing in this simple query..

$args = array(
    'post_type'  => 'wine',
    'orderby'    => 'meta_value menu_order',
    'meta_query' => array(
            array(
                'key'     => 'producer',
                'compare' => 'EXISTS',
            )
    ),
    'tax_query'   => array(
            array(
                'taxonomy' => 'region',
                'field'    => 'slug',
                'terms'    => $region_slug // your term here (the region)
            )
        ),
);
$wine_query = new WP_Query( $args );

// Then do your loop 

It would be pretty easy to still insert heading sections whenever the producer value changes (just check for it as part of the loop)

I used the same plugin you did to setup the custom fields – my post_type was ‘wine’, and taxonomies where ‘producer’ and ‘region’.