Taxonomy List Based On Post ID

Quick Summary
- Pass a post ID to get_the_terms and get_term_link to list that post's categories as archive links, even outside the main loop.
- For a comma-separated list of links, get_the_term_list takes the post ID, taxonomy, text before the list and separator in one line.
- A post without terms makes get_the_terms return false and the foreach throw a PHP warning, so wrap the loop in a check.
These two snippets list the categories of a specific WordPress post as links to their archive pages when all you have is the post’s ID. That’s useful outside the main loop, for example in a related-posts block or a custom query where you need the categories of another post.
Both expect a variable $main_post_id that holds the ID of the post you’re interested in. Set it before the code runs, for example to get_the_ID() inside a loop or to a fixed number, and add the code to the theme template where the list should appear.
Method 1: loop through the terms
<?php $terms = get_the_terms( $main_post_id, 'category' ); ?>
<?php foreach( $terms as $term ): ?>
<a href="<?php echo get_term_link($term->slug, 'category'); ?>" class="catg-title"><?php echo $term->name; ?></a>
<?php endforeach; ?>get_the_terms()returns the post’s terms in thecategorytaxonomy as an array of term objects.get_term_link()builds the URL of each category archive, and$term->nameis the link text.- Every link gets the class
catg-title, so you can style it or change the markup freely.
If the post has no terms, get_the_terms() returns false and the foreach throws a PHP warning. Wrap the loop in a check when that can happen, for example with a custom taxonomy.
Method 2: one line with get_the_term_list()
If a comma-separated list of links is all you need, get_the_term_list() does the whole job. Its arguments are the post ID, the taxonomy, the text before the list (empty here) and the separator between items (a comma and a space).
<?php echo get_the_term_list( $main_post_id, 'category', '', ', ' ); ?>To list tags or a custom taxonomy instead of categories, replace category with that taxonomy’s name, such as post_tag. In method 1, change it in both get_the_terms() and get_term_link(). For names without links, see printing custom taxonomy terms as a comma-separated list.
Related articles
- term functions that work for custom post types: when the_category() returns nothing
- linking to a post’s first category archive: when you need just one term link

