tag_exists()
Checks if the specified tag exists. If it exists, it returns the ID or an array of data for that tag.
Tags or labels refer to the taxonomy terms post_tag that are originally registered in WordPress and used in Posts.
This function is defined only in the admin area, so if called on the front end, it will result in an error:
Fatal error: Uncaught Error: Call to undefined function tag_exists()
To make the function work on the front end, you need to include the file:
require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
With WP 6.0, the function works with caching and uses get_terms().
Before WP 6.0, this function performed a database query. get_term_by() can be used for the same purpose, except that it uses caching.
No Hooks.
Returns
Mixed. null/number/array
-
Array — when the tag is found:
[ 'term_id' => 'term id', 'term_taxonomy_id' => 'taxonomy id' ]
-
null — when the tag does not exist.
- 0 — when 0 is passed to the function instead of the tag ID.
Usage
tag_exists( $tag_name );
- $tag_name(string/number) (required)
- The tag to check. You can specify the name, the alternative name (slug), or the ID.
Examples
#1 Check the tag for existence:
// Check the existence of tags
$tag = tag_exists( 'Menswear' );
if( $tag ){
print_r( $tag );
}
If the tag exists, it will print something like this:
Array ( [term_id] => 541 [term_taxonomy_id] => 541 )
Why term_id and term_taxonomy_id are equal, read What are Taxonomies in WordPress.
#2 term_exists and tag_exists
Function tag_exists() is a wrapper for function term_exists() to more easily check default taxonomy terms post_tag (tags, tags). The following two variants are identical in result:
$tag_name = 'Tag #1'; // Option 1 tag_exists( $tag_name ); // Option 2 term_exists( $tag_name, 'post_tag' )
Changelog
| Since 2.3.0 | Introduced. |
tag_exists() tag exists code WP 7.0
function tag_exists( $tag_name ) {
return term_exists( $tag_name, 'post_tag' );
}