Get The Slug and Name From Custom Taxonomy

For a project I’m working on, I’ve been diving into Custom Post Types and Custom Taxonomies. It’s a lot of fun…the kind of fun that if you don’t do it right makes you want to blow up your computer. I came across an interesting issue where I wanted to link via the category slug, but not to the archive.

I looked around for a couple of hours and finally found this thread on and decided to go for it. It partially worked, but there was one piece missing. I could get the slug for the URL, but I also needed the name.

Duplicating the variable and changing slug to name got me the name of the custom category. Perfect. I tossed it all together and it now lies in the snippet below.

<?php if (have_posts()) : while (have_posts()) : the_post(); 

		$terms = get_the_terms( $post->id, 'custom-taxonomy' ); // get an array of all the terms as objects.
		$term_slug = array(); // save the slugs in an array
		$term_name = array(); // save the slugs in an array

		foreach( $terms as $term ) {
		    $term_slug[] = $term->slug; // this grabs the hyphenated slug
		    $term_name[] = $term->name; // this grabs the actual name

<strong>Project Type:</strong> <a href="<?php echo home_url(); ?>/projects/<?php echo $term_slug[0]; ?>"><?php echo $term_name[0]; ?></a>

Feel free to use it however you want. One caveat I found was if no category is selected and you have the above code in the loop, the loop farts out or throws an error, which is understandable. In my case a category will ALWAYS be chosen. It’s a bit of a hack, but it works. Suggestions on how to improve it are welcome.

For more snippets check out some of the links below, or go look at ‘My Gists’ on GitHub.

Photo Credit: The Octodex #62

Notify of
Inline Feedbacks
View all comments

John Hartley is a Director of Product Engineering at Beam Dental in Columbus, OH. With 5+ years of leadership experience he has worked in startups, agencies, and began his career as a freelance Front End Developer. Always looking to iterate, this blog is a place for him to share his knowledge as well as hone his craft, challenge assumptions, and build a strong base of leadership and management knowledge. Connect with him on LinkedIn

Would love your thoughts, please comment.x