add_term_meta()WP 4.4.0

Adds a meta-field (additional field) for the specified taxonomy term (categories, tags ...).

No Hooks.

Returns

Int|false|WP_Error.

  • ID - in case of successful addition.
  • WP_Error - in case of incorrectly specified term_id of the taxonomy.
  • False - in case of an error during the addition.

Usage

add_term_meta( $term_id, $meta_key, $meta_value, $unique );
$term_id(int) (required)
ID of the taxonomy term.
$meta_key(string) (required)
Key of the meta field.
$meta_value(mixed) (required)
Value of the meta field.
$unique(boolean)

Is this value unique or not.

  • false - means that multiple identical keys can be defined for this taxonomy term.
  • true - means that the key for this term can only be one, i.e., if such a key already exists, the function will not add anything.
    Default: false

Examples

0

#1 Adding multiple values for one meta field

$term_id  = 62;
$meta_key = 'test_meta_field';

// add
add_term_meta( $term_id, $meta_key, 'Hello world', false );
add_term_meta( $term_id, $meta_key, 'Hello world 2', false );

// see what you get
$fields = get_term_meta( $term_id, $meta_key );

print_r( $fields );

/* will output
Array
(
	[0] => Hello world
	[1] => Hello world 2
)
*/
-5

#2 Add a term meta field with a single value

$term_id = 62;
$meta_key = 'test_meta_field';

add_term_meta( $term_id, $meta_key, 'Hello world', true );

// Output
echo get_term_meta( $term_id, $meta_key, true ); //> Hello world

Try to add another field with the same key

$done = add_term_meta( $term_id, $meta_key, 'Hello World 2', true );

var_dump( $done ); // bool(false)

Changelog

Since 4.4.0 Introduced.

add_term_meta() code WP 7.0

function add_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
	if ( wp_term_is_shared( $term_id ) ) {
		return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
	}

	return add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
}