term_exists()WP 3.0.0

Check if a given taxonomy element exists. Returns either term ID or a term data if the element (term) exists.

Formerly is_term(), introduced in 2.3.0.

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Since WP 6.0. function works with object cache and uses get_terms().

Before WP 6.0. This function runs a database query. get_term_by() can be used for the same purpose, except it uses the term cache.

1 time — 0.000419 sec (fast) | 50000 times — 14.74 sec (slow) | PHP 7.0.14, WP 4.7
Hooks from the function

Return

Mixed. null/int/array

  • String - Term ID as string — when taxonomy is not specified and term exists. E.g. term_exists( 395 ) > string(3) "395".

  • Array — when taxonomy is specified and term exists:

    [
    	'term_id' => 'term id',
    	'term_taxonomy_id' => 'taxonomy id'
    ]
  • null — when the term does not exist.

  • 0 — when 0 passed to the function instead of the term ID.

Usage

term_exists( $term, $taxonomy, $parent_term );
$term(string|int) (required)

The term you want to check. You can specify a name, an alternate name (slug), or an ID.

If an ID is specified, the value must be of type "number" but not "string" as a number. For example 12, not '12'.

$taxonomy(string)
Name of the taxonomy the function will work with. It is not necessary to specify it when term IDs is passed in $term paremeter.
Default: ''
$parent(string|int)
The ID of the parent term under which the specified taxonomy item is supposed to be searched.
Default: null

Examples

0

#1 Check if term exists (in any taxonomy)

$term = term_exists( 'miscellaneous' );
//returns the ID of the taxonomy element with the 'miscellaneous' slug

$term = term_exists( 'Men Clothes' );
//returns the ID of the taxonomy element named 'Men Clothes'
0

#2 Check if term exists in specific taxonomy

Check if my_tax taxonomy term exists:

$term = term_exists( 'Men clothing', 'my_tax' );
//returns an array
//    [term_id] => 80
//    [term_taxonomy_id] => 84

// taxonomy element ID
echo $term['term_id'];

// taxonomy element ID in taxonomy structure
echo $term['term_taxonomy_id'];

Check if the Uncategorized category exists:

$term = term_exists( 'Uncategorized', 'category' );

if ( $term !== 0 && $term !== null ) {
	echo 'Uncategorized category exists!';
}
0

#3 Since WP 6.0 term_exists() is cached

So for code that uses this function you need to make sure that term_exists() gets an uncached result, there are two ways to do this:

1) Using the new filter term_exists_default_query_args:

$callback = function ( $args ) {
   $args['cache_domain'] = microtime();
};

add_filter( 'term_exists_default_query_args',  $callback );

$check = term_exists( 123, 'category' );

remove_filter( 'term_exists_default_query_args',  $callback );

2) Using wp_suspend_cache_invalidation():

wp_suspend_cache_invalidation( true );

$check = term_exists( 123, 'category' );

wp_suspend_cache_invalidation( false );

Read more here: https://make.wordpress.org/core/2022/04/28/taxonomy-performance-improvements-in-wordpress-6-0/

Notes

  • Global. true|false. $_wp_suspend_cache_invalidation

Changelog

Since 3.0.0 Introduced.
Since 6.0.0 Converted to use get_terms().

term_exists() code WP 6.4.3

function term_exists( $term, $taxonomy = '', $parent_term = null ) {
	global $_wp_suspend_cache_invalidation;

	if ( null === $term ) {
		return null;
	}

	$defaults = array(
		'get'                    => 'all',
		'fields'                 => 'ids',
		'number'                 => 1,
		'update_term_meta_cache' => false,
		'order'                  => 'ASC',
		'orderby'                => 'term_id',
		'suppress_filter'        => true,
	);

	// Ensure that while importing, queries are not cached.
	if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
		$defaults['cache_results'] = false;
	}

	if ( ! empty( $taxonomy ) ) {
		$defaults['taxonomy'] = $taxonomy;
		$defaults['fields']   = 'all';
	}

	/**
	 * Filters default query arguments for checking if a term exists.
	 *
	 * @since 6.0.0
	 *
	 * @param array      $defaults    An array of arguments passed to get_terms().
	 * @param int|string $term        The term to check. Accepts term ID, slug, or name.
	 * @param string     $taxonomy    The taxonomy name to use. An empty string indicates
	 *                                the search is against all taxonomies.
	 * @param int|null   $parent_term ID of parent term under which to confine the exists search.
	 *                                Null indicates the search is unconfined.
	 */
	$defaults = apply_filters( 'term_exists_default_query_args', $defaults, $term, $taxonomy, $parent_term );

	if ( is_int( $term ) ) {
		if ( 0 === $term ) {
			return 0;
		}
		$args  = wp_parse_args( array( 'include' => array( $term ) ), $defaults );
		$terms = get_terms( $args );
	} else {
		$term = trim( wp_unslash( $term ) );
		if ( '' === $term ) {
			return null;
		}

		if ( ! empty( $taxonomy ) && is_numeric( $parent_term ) ) {
			$defaults['parent'] = (int) $parent_term;
		}

		$args  = wp_parse_args( array( 'slug' => sanitize_title( $term ) ), $defaults );
		$terms = get_terms( $args );
		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			$args  = wp_parse_args( array( 'name' => $term ), $defaults );
			$terms = get_terms( $args );
		}
	}

	if ( empty( $terms ) || is_wp_error( $terms ) ) {
		return null;
	}

	$_term = array_shift( $terms );

	if ( ! empty( $taxonomy ) ) {
		return array(
			'term_id'          => (string) $_term->term_id,
			'term_taxonomy_id' => (string) $_term->term_taxonomy_id,
		);
	}

	return (string) $_term;
}