Ultimate Web Tips

your Wordpress, jQuery, PHP, MySQL, Linux and CSS guide to a successful website

Get custom taxonomy name from post id with get_the_terms

December 9th, 2011 Wordpress, by Joakim Ling.

If you’ve registered a custom taxonomy it’s a bit different to get data from than how you’d normally do for categories.

Let’s say we want to add Brands as a taxonomy to our posts

register_taxonomy( 'brands', 'post', array('labels'=>array('name'=>'Brands')));

To get the category from post id we use get_the_category, but that only look for the terms in category taxonomy. So we need to get the custom term list from get_the_terms, as we can specify which taxonomy to look for.

$brands = get_the_terms( $postID, 'brands' );

get_the_terms

Will return an array with all brands selected in this case, false or wp_error if invalid taxonomy given.

So in a real example you should use something similar to this:

<?php
global $post;
$brands = get_the_terms( $post->ID, 'brands' );
if ($brands && !is_wp_error($brands)): 
	$brand_names = array();
	foreach ($brands as $brand)
		$brand_names[] = $brand->name;
	$brands = implode(", ", $brand_names);
?>
<p class="posts brands">
	Brands: <span><?php echo $brands; ?></span>
</p>
<?php endif; ?>

If you want with links look for get_the_term_list.

Themedy Thesis & Genesis Skin Club

Themedy is a premium skin marketplace offering quality child themes for the some of the most popular Wordpress frameworks like Thesis & Genesis. Read more

Back Top