Last Updated: February 18, 2019
· jackabox

Looping through custom posts by custom taxonomies in WordPress

Recently I had been asked to set up a loop in WordPress which looped through any terms assigned to the custom post and displayed them on the page. The below code is a pretty simple way, I found, to do it.

// Get all the categories
$categories = get_terms( 'service-category' );

// Loop through all the returned terms
foreach ( $categories as $category ):

    // set up a new query for each category, pulling in related posts.
    $services = new WP_Query(
            'post_type' => 'services',
            'showposts' => -1,
            'tax_query' => array(
                    'taxonomy'  => 'service-category',
                    'terms'     => array( $category->slug ),
                    'field'     => 'slug'

<h3><?php echo $category->name; ?></h3>
<?php while ($services->have_posts()) : $services->the_post(); ?>
    <li><?php the_title(); ?></li>
<?php endwhile; ?>

    // Reset things, for good measure
    $services = null;

// end the loop

Full article was written on my blog at:

1 Response
Add your response

Thank you form the bottom of my heart!!

over 1 year ago ·