If you need nested queries, first you should think about, which data is needed. In your example you need all terms of a tanonomy as well as all posts belonging to each taxonomy. So the first step should be to find a way to loop through all terms of a taxonomy:
/* TAXONOMIES */
// args
$args_tax = array(
'order' => ASC);
// get terms
$terms = get_terms($tax, $args_tax);
$count = count($terms);
if ($count > 0) {
echo "<ul>";
foreach ($terms as $term) {
echo "<li>";
echo $term->name;
echo "</li>";
}
echo "</ul>";
}
http://codex.wordpress.org/Function_Reference/get_terms
In the next step you have to loop through the posts:
/* CPT POSTS */
// args
$args_cpt = array(
'post_type' => $cpt,
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $term->slug
)
)
);
// get posts
$tax_query = new WP_Query($args_cpt);
if ($tax_query->have_posts()) {
echo "<ul>";
while ($tax_query->have_posts()) {
$tax_query->the_post();
echo "<li>";
echo get_the_title();
echo "</li>";
}
echo "</ul>";
}
wp_reset_postdata();
http://codex.wordpress.org/Class_Reference/WP_Query
Now you have to combine the two loops. For example in a function placed in functions.php:
/**
* RFRQ
* the_posts_by_tax
*/
if (!function_exists('the_posts_by_tax')) {
function the_posts_by_tax($cpt, $tax) {
/* TAXONOMIES */
// args
$args_tax = array(
'order' => ASC);
// get terms
$terms = get_terms($tax, $args_tax);
$count = count($terms);
if ($count > 0) {
echo "<ul>";
foreach ($terms as $term) {
echo "<li>";
echo $term->name;
/* CPT POSTS */
// args
$args_cpt = array(
'post_type' => $cpt,
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $term->slug
)
)
);
// get posts
$tax_query = new WP_Query($args_cpt);
if ($tax_query->have_posts()) {
echo "<ul>";
while ($tax_query->have_posts()) {
$tax_query->the_post();
echo "<li>";
echo get_the_title();
echo "</li>";
}
echo "</ul>";
}
wp_reset_postdata();
echo "</li>";
}
echo "</ul>";
}
}
}
You can call your loop through:
the_posts_by_tax($cpt, $tax)