update_term_meta()WP 4.4.0

Updates the metadata of a taxonomy term (categories, tags ...).

Use the $prev_value parameter to update an already existing value when there are multiple fields with the same key.

If the field does not exist at the time of the function call, it will be added.

The taxonomy name is not passed to the function, as each term has a unique ID ($term_id) and is associated with a specific taxonomy.

No Hooks.

Returns

Int|true|false|WP_Error. Will return:

  • ID if the key did not previously exist and the field was added.
  • true on successful update of an existing field.
  • WP_Error in case of an incorrectly specified term_id of the taxonomy.
  • False in case of an error during the update process.

Usage

update_term_meta( $term_id, $meta_key, $meta_value, $prev_value );
$term_id(number) (required)
ID of the taxonomy term.
$meta_key(string) (required)
Field key.
$meta_value(mixed) (required)
Value of the field to be written.
$prev_value(mixed)
Previous value. Needed to update a specific field when there are multiple fields with the same key.
Default: ''

Examples

2

#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.

update_term_meta() code WP 6.9

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