[wp-hackers] has_tag()

Otto otto at ottodestruct.com
Fri Apr 4 18:05:54 GMT 2008


On Fri, Apr 4, 2008 at 10:45 AM, Mistah P <mistahp.hackers at gmail.com> wrote:
>  That's nice work, Otto. It does exactly what I'd expect.
>
>  I can see one potential issue though, and this may be splitting hairs.
>  Should there be a way to distinguish a numeric tag slug from a tag id?
>  Examples: the number 666 might be a tag people use in discussions of
>  occultism and the number 42 might be a tag used by Douglas Adams fans.
>
>  Should there be a way to identify the type of identifier the function
>  should be looking for? I'm not advocating that, as it would probably
>  be pretty uncommon, but it may be worth discussing.

Well, the existing functions like is_category and such don't do that.
So they would have the same problem.

However, the existing functions in 2.5 also allow you to input arrays
of things, so I figured that was worth adding as well. If you give
this one an array of tags, has_tag will return true if any of them
match.

Note that if you added the third parameter of "true" to the "in_array"
functions below, then the strict checking mode would prevent the issue
you're concerned about with it mixing up id's and slugs.

/**
 * has_tag() - Check if the current post has the given tag
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 2.5.1
 *
 * @uses wp_get_object_terms() Gets the tags.
 *
 * @param string|int|array $tag Optional. The tag name/id/slug or
array of them to check for
 * @return bool True if the current post has the given tag, or any
tag, if no tag specified
 */
function has_tag($tag = '') {
	global $post;
	$taxonomy = "post_tag";

	if ( !in_the_loop() ) return false; // in-the-loop function

	$post_id = (int) $post->ID;

	$terms = get_object_term_cache($post_id, $taxonomy);
	if (empty($terms))
	       	$terms = wp_get_object_terms($post_id, $taxonomy);

	if (empty($tag)) return (!empty($terms));
	
	$tag = (array) $tag;
	
	foreach($terms as $term) {
		if ( in_array( $term->term_id, $tag ) )
			return true;
		elseif ( in_array( $term->name, $tag ) )
			return true;
		elseif ( in_array( $term->slug, $tag ) )
			return true;		
	}

	return false;
}


More information about the wp-hackers mailing list