Skip to content

Instantly share code, notes, and snippets.

@mattbanks
Created April 2, 2014 16:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mattbanks/9938089 to your computer and use it in GitHub Desktop.
Save mattbanks/9938089 to your computer and use it in GitHub Desktop.
Loop through each taxonomy term, run a new WP_Query in each term
<?php
// Get terms
// http://codex.wordpress.org/Function_Reference/get_terms
// use $args array in second parameter if needed
$my_categories = get_terms( 'TERM_NAME_HERE' );
$my_categories_count = count( $my_categories );
if ( $my_categories_count > 0 && is_array( $my_categories ) ) {
echo '<div class="wrap">';
foreach ( $my_categories as $single_cat ) { ?>
<h2><?php echo $single_cat->name; ?></h2>
<?php
$cat_posts_args = array(
'post_type' => 'product',
'order' => 'ASC',
'orderby' => 'date',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $single_cat->term_id,
'include_children' => false
)
)
);
$cat_posts = new WP_Query( $cat_posts_args );
if ( $cat_posts->have_posts() ) :
echo '<p>';
while ( $cat_posts->have_posts() ) : $cat_posts->the_post(); ?>
<a href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span>: <?php echo get_the_excerpt(); ?></a><br>
<?php endwhile;
echo '</p>';
else :
if ( !$parent ) echo '<p>No products found.</p>';
endif;
wp_reset_postdata();
} // end foreach
echo '</div>';
}
@braddalton
Copy link

Thanks Matt Banks. I tested the tax_query args from this loop and they still work 5 years on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment