[wp-hackers] has_tag()

Otto otto at ottodestruct.com
Fri Apr 4 14:47:08 GMT 2008


On Fri, Apr 4, 2008 at 8:26 AM, Mistah P <mistahp.hackers at gmail.com> wrote:
>  That is a handy function. I'd like to see that in core, provided it's
>  made a little more flexible (like returning true if there's any tag
>  when nothing is passed to the function, and maybe checking tags by id
>  or slug).

First stab at that, tell me if I missed anything:

/**
 * 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 for returning. Args can
be found here
 *
 * @param string|int $tag Optional. The tag name/id/slug 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));

	foreach($terms as $term) {
		if($term->name == $tag) return true;
		if($term->slug == $tag) return true;
		if($term->term_id == $tag) return true;
	}
	
	return false;
}


More information about the wp-hackers mailing list