update_term_meta()WP 4.4.0

Updates term metadata.

Use the $prev_value parameter to differentiate between meta fields with the same key and term ID.

If the meta field for the term does not exist, it will be added.

No Hooks.

Return

Int|true|false|WP_Error. Meta ID if the key didn't exist. true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database. WP_Error when term_id is ambiguous between taxonomies.

Usage

update_term_meta( $term_id, $meta_key, $meta_value, $prev_value );
$term_id(int) (required)
Term ID.
$meta_key(string) (required)
Metadata key.
$meta_value(mixed) (required)
Metadata value. Must be serializable if non-scalar.
$prev_value(mixed)
Previous value to check before updating. If specified, only update existing metadata entries with this value. Otherwise, update all entries.
Default: ''

Examples

0

#1 Set a small text for the post tag and display it on the tag page

Set the text 'Hello World' for the tag with id 702 and save it to the test_meta_field meta.

update_term_meta( 702, 'test_meta_field', 'Hello world' );

Display it on the tag page:

$fields = get_term_meta( get_queried_object_id(), 'test_meta_field' );

if( $fields && is_array( $fields ) ){
	echo $fields[0];
}
0

#2 Multiple metas with the same key

Add several fields with the same key:

// add data
$term_id  = 702;
$meta_key = 'test_meta_field';

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

// gets the data just added
$fields = get_term_meta( $term_id, $meta_key );

print_r( $fields );

/* Result:
Array
(
	[0] => Hello world
	[1] => Hello world 2
)
*/
0

#3 Update the field with the specified value

We have 2 meta-fields with the same key test_meta_field but different values, we only need to update the field with the value Hello world:

update_term_meta( 702, 'test_meta_field', 'Hello NEW world', 'Hello world' );

Changelog

Since 4.4.0 Introduced.

Code of update_term_meta() WP 6.0.1

function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
	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 update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
}