add_term_meta()WP 4.4.0

Adds metadata to a term.

No Hooks.

Return

Int|false|WP_Error. Meta ID on success, false on failure. WP_Error when term_id is ambiguous between taxonomies.

Usage

add_term_meta( $term_id, $meta_key, $meta_value, $unique );
$term_id(int) (required)
Term ID.
$meta_key(string) (required)
Metadata name.
$meta_value(mixed) (required)
Metadata value. Must be serializable if non-scalar.
$unique(true|false)
Whether the same key should not be added.
Default: false

Examples

0

#1 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)
0

#2 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
)
*/

Changelog

Since 4.4.0 Introduced.

add_term_meta() code WP 6.5.2

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 );
}