Link to the First Category Page of a Custom Post

Quick Summary

  • In a custom post type's single template, get_the_terms reads your taxonomy's terms, such as material-category, and array_shift takes the first.
  • get_term_link builds that term's archive URL, and the fixed category Link text can be swapped for $term->name wrapped in esc_html.
  • If the post has no terms, $link stays undefined and the href is empty, so print the link only inside the if block.

On the single page of a custom post type, you may want a link back to the archive of the post’s category. Custom post types usually use a custom taxonomy, so this snippet uses get_the_terms() instead of the category functions, takes the first term and prints a link to its archive page.

Place it in the single template of your post type, such as single-{post_type}.php, and replace material-category with your taxonomy slug.

PHP
<?php 
   $terms = get_the_terms( $post->ID, 'material-category' );
   if ( !empty( $terms ) ){
   // get the first term
   $term = array_shift( $terms );
   $link = get_term_link( $term );
   }
?>
<a href="<?php echo $link; ?>">category Link</a>

How it works

  • get_the_terms() returns the current post’s terms in material-category, or false if it has none.
  • array_shift() takes the first term from that array.
  • get_term_link() builds the URL of that term’s archive page.
  • The link text is fixed as category Link. To show the category name instead, print $term->name, wrapped in esc_html().

If the post has no terms, $link is never set, so PHP reports an undefined variable and the link is printed with an empty href. Move the link inside the if block, or set $link to an empty string first and only print the link when it has a value. Passing the URL through esc_url() is also a good habit.

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