The add_term_meta() WordPress PHP function is used to add metadata to a term.
Usage
An example of using this function would be to add a new custom field to a term. The custom field might have a key name ‘my_term_key’ and a value ‘new_term’. Here’s how you would use the function:
add_term_meta(12, 'my_term_key', 'new_term');
Parameters
- $term_id (int) – The ID of the term that you want to add metadata to.
- $meta_key (string) – The name of the metadata you want to add.
- $meta_value (mixed) – The value of the metadata. This needs to be serializable if it’s not a scalar.
- $unique (bool) – Optional. If set to true, the function won’t add the metadata if the term already has metadata with the same key. The default is false.
More information
See WordPress Developer Resources: add_term_meta()
Examples
Adding a New Custom Field
// You want to add a new custom field 'color' to term with ID 15, with the value 'red' add_term_meta(15, 'color', 'red');
Adding Unique Metadata
// You want to add a unique 'color' metadata to term with ID 15, with the value 'red' // If 'color' metadata already exists for this term, it won't be added add_term_meta(15, 'color', 'red', true);
Adding Non-Scalar Metadata
// You want to add a non-scalar value, an array in this case, as metadata add_term_meta(20, 'coordinates', array(40.7128, 74.0060));
Adding Metadata to Multiple Terms
// You want to add 'color' metadata to multiple terms $term_ids = array(10, 15, 20); foreach ($term_ids as $term_id) { add_term_meta($term_id, 'color', 'blue'); }
Updating Metadata if It Exists
// You want to add 'color' metadata to a term, but only if 'color' metadata doesn't already exist for that term $term_id = 25; if (!get_term_meta($term_id, 'color')) { add_term_meta($term_id, 'color', 'green'); }