X

has_term() function

Ok, you created a Custom Post Type and some Custom Taxonomies for it. Now you want to check wether your post has a term (aka category) from the new taxonomy. There’s no built-in function for this, or at least none that I know of (but I may be wrong).

Anyway, this simple function requires 2 parameters: 1) the term name, 2) the taxonomy name. It returns a boolean. Just paste it in your functions.php file and you’re good to go.< Oh, I almost forgot: term names are case-sensitive, so type carefully.

Code Snippet:

<?php
function has_term($term_name, $taxonomy_name) {
	$terms = get_terms($taxonomy_name, 'fields=names');
	for ($i=0; $i < count($terms); $i++) {
		if ($terms&#91;$i&#93; == $term_name) {
			return true;
		}
	} return false;
}
?>

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!