Using get_term_meta to retrieve custom metadata for WordPress terms

The WordPress get_term_meta function retrieves metadata for a specified term in a taxonomy. This can be useful for accessing additional information associated with a term, such as custom fields or attributes.

By using get_term_meta, developers can retrieve and display specific metadata related to a term, allowing for more customized and dynamic content presentation on their WordPress site.

Parameters accepted by get_term_meta function

  • $term_id (int, required): Term ID.
  • $key (string, optional, default value: ”): The meta key to retrieve. By default, returns data for all keys.
  • $single (bool, optional, default value: false): Whether to return a single value. This parameter has no effect if $key is not specified.

Value returned by get_term_meta function

The function returns:

  • An array of values if $single is false.
  • The value of the meta field if $single is true.
  • False for an invalid $term_id (non-numeric, zero, or negative value).
  • An empty string if a valid but non-existing term ID is passed.

Examples

How to get term meta data in WordPress

Use the get_term_meta function to retrieve meta data associated with a term in WordPress.

$term_id = 5;
$meta_key = 'color';
$meta_value = get_term_meta( $term_id, $meta_key, true );

This code snippet retrieves the meta value for the meta key ‘color’ associated with the term ID 5.

How to check if term meta data exists in WordPress

Use the get_term_meta function to check if meta data exists for a specific term in WordPress.

$term_id = 7;
$meta_key = 'image';
$image_exists = get_term_meta( $term_id, $meta_key, true );

if ( $image_exists ) {
 echo 'Image exists for term ID 7';
} else {
 echo 'No image found for term ID 7';
}

This code snippet checks if the meta key ‘image’ exists for the term ID 7, and then outputs a message based on the result.

How to update term meta data in WordPress

Use the update_term_meta function to update meta data associated with a specific term in WordPress.

$term_id = 10;
$meta_key = 'featured';
$new_meta_value = 'yes';
update_term_meta( $term_id, $meta_key, $new_meta_value );

This code snippet updates the meta value for the meta key ‘featured’ to ‘yes’ for the term ID 10.

Conclusion

In conclusion, the get_term_meta function is an effective feature for retrieving metadata for a specific term in WordPress. By using this function, developers can easily access and manipulate custom metadata associated with taxonomy terms, enhancing the flexibility and functionality of their websites. With its simple syntax and wide range of parameters, get_term_meta provides a convenient way to customize and extend the capabilities of WordPress taxonomies. Overall, this function is a valuable resource for developers looking to create dynamic and customizable websites using WordPress.

Related WordPress Functions