Using WordPress ‘has_tag()’ PHP function

The has_tag() WordPress PHP function checks if the current post has any of the given tags.

Usage

has_tag( $tag, $post );

Example:

Input:

if (has_tag('featured', 42)) {
  echo "Post 42 has the 'featured' tag.";
} else {
  echo "Post 42 does not have the 'featured' tag.";
}

Output:

Post 42 has the 'featured' tag.

Parameters

  • $tag (string|int|array) (Optional): The tag name, term_id, slug, or an array of them to check for. Default: ”
  • $post (int|WP_Post) (Optional): Post to check. Defaults to the current post. Default: null

More information

See WordPress Developer Resources: has_tag()

Examples

Display tags if the post has any

This code will display the tags of the post if it has any. It should be used inside the loop.

if (has_tag()) {
  the_tags();
} else {
  // Article untagged
}

Display tags or categories based on post metadata

This code will display the tags if the post has any; otherwise, it will display the categories if the post has any. If neither tags nor categories are present, it will execute a different action.

if (has_tag()) {
  the_tags(); // show tags
} elseif (has_category()) {
  the_category(); // show category
} else {
  // do something different
}

Check if a post has a specific tag

This code checks if the current post has a specific tag, and then displays a message accordingly.

if (has_tag('featured')) {
  echo "This post is featured.";
} else {
  echo "This post is not featured.";
}

Check if a specific post has a specific tag

This code checks if a specific post (ID: 42) has a specific tag, and then displays a message accordingly.

if (has_tag('featured', 42)) {
  echo "Post 42 is featured.";
} else {
  echo "Post 42 is not featured.";
}

Check if a post has any of multiple tags

This code checks if the current post has any of the specified tags, and then displays a message accordingly.

if (has_tag(array('featured', 'important', 'highlight'))) {
  echo "This post has at least one of the specified tags.";
} else {
  echo "This post does not have any of the specified tags.";
}