Get the Custom Taxonomy Terms of a Custom Post in a Loop

Quick Summary

  • Inside a custom post type loop, get_the_terms() with get_the_ID() fetches the post's Speaker-Category terms, and a foreach echoes each slug plus a space.
  • Space-separated slugs work as CSS classes, for example to filter a speaker grid with MixItUp; echo $sp_term->name for readable names instead.
  • The is_array() check skips the loop when get_the_terms() returns false (no terms) or a WP_Error (a wrong taxonomy name), so those posts print nothing instead of PHP warnings.

Inside a WordPress loop for a custom post type, this snippet prints the slugs of the terms the current post has in a custom taxonomy, here Speaker-Category. The slugs come out separated by spaces, which makes them handy as CSS classes, for example to filter a grid of speakers by category with a library such as MixItUp (see opening a MixItUp grid on a default filter).

Place it in the template that runs the loop, where you want the slugs to appear.

PHP
<?php
$postid = get_the_ID();
$sp_terms = get_the_terms( $postid, 'Speaker-Category' );
?>
<?php if ( is_array( $sp_terms ) ) : foreach( $sp_terms as $sp_term ): ?><?php echo esc_attr( $sp_term->slug ); ?> <?php endforeach; endif; ?>

How it works

  • get_the_ID() returns the ID of the current post in the loop.
  • get_the_terms() gets the terms that post has in the given taxonomy, as an array of term objects.
  • The foreach loop echoes each term’s slug followed by a space.

Adapting it

Replace Speaker-Category with the name of your taxonomy, written exactly as it was registered with register_taxonomy(). To show readable names instead of slugs, echo $sp_term->name. For names in a comma-separated list, see separating taxonomy terms with commas.

get_the_terms() returns false when a post has no terms and a WP_Error when the taxonomy name is wrong. The is_array() check skips the loop in both cases, so those posts print nothing instead of PHP warnings. esc_attr() keeps the slugs safe inside an HTML attribute such as class.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More