Separate Custom Post Type Taxonomy by Comma

Quick Summary

  • Inside the loop, get_the_terms() returns the post's guest terms, and a counter compared with count() puts a comma after every name but the last.
  • For linked names, get_the_term_list() with a comma and a space as the separator builds the same list of term archive links in one call.
  • Replace guest with your taxonomy name, and check for false before the foreach, since posts without terms otherwise trigger a PHP warning.

When a custom post type has a taxonomy with several terms per post, you often want them printed as a readable list, with commas between the names but not after the last one. This snippet does that for a guest taxonomy, for example the guests of a podcast episode.

Use it inside the loop of your post type’s single or archive template. If you need the term slugs instead, for example as CSS classes, see getting a post’s custom taxonomy slugs in a loop.

PHP
<?php
$postid = get_the_ID();
$ep_guests = get_the_terms($postid, 'guest');
?>
<?php
$guest_count = 1;
foreach ($ep_guests as $ep_guest):
?>
<?php
 echo $ep_guest->name;
echo ($guest_count < count($ep_guests)) ? ", " : "";
 $guest_count++; ?>
<?php endforeach; ?>

How it works

  • get_the_ID() gets the current post’s ID, and get_the_terms() returns its guest terms as an array of term objects.
  • $guest_count tracks the position in the loop, starting at 1.
  • After each name, the code compares $guest_count with the total from count(). If more terms follow, it prints a comma and a space; after the last name it prints nothing.

Adapting it

Change guest to your own taxonomy name. If a post can have no terms, check the result before the loop: get_the_terms() returns false in that case, and the foreach throws a PHP warning. Wrapping $ep_guest->name in esc_html() is a good habit when you print it.

If you want each name to link to its term archive, get_the_term_list() with a comma and a space as the separator gives you a comma-separated list of links in one call.

More approaches are discussed in this WordPress Stack Exchange question: Separate custom post type taxonomy by comma.

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