get_term_meta()
Gets the value of the specified meta-field of a taxonomy term (categories, tags, etc.). You can get all values as an array.
The function works similarly to get_post_meta(), except that it retrieves custom fields of taxonomy terms rather than posts.
Additionally, there is a difference in that there is no admin interface for adding fields for a taxonomy term. For these purposes, you should use the functions: add_term_meta() update_term_meta().
No Hooks.
Returns
Mixed
. - If $single = false, then an array of values of the specified meta-field. If there are no values, then an empty array array()
.
- If $single = true, then a single value of the specified meta-field (the first in the array), which can be anything (string, number, object, array).
Usage
get_term_meta( $term_id, $key, $single );
- $term_id(number) (required)
- ID of the taxonomy term.
- $key(string)
- Key of the meta field.
Default: '' - $single(boolean)
How to return the value.
false
- array of valuestrue
- single value (the first from the array if there are multiple values)
Default: false
Examples
#1 Get all values of test_meta_field
term meta field
$fields = get_term_meta( 10 , 'test_meta_field', false ); if( $fields ){ print_r( $fields ); /* will output Array ( [0] => Hello world [1] => Hello world ) */ } else { // no metadata... }
#2 Get the value of the meta on the term archive page
Suppose we have a meta field test_meta_field
category 65 that contains (string) What a nice day
and we need to display this string on the category page.
// the current category, let's assume we visit category 65 page $term_id = get_query_var( 'cat' ); echo get_term_meta( $term_id, 'test_meta_field', true ); //> What a nice day
Another way. We can use get_queried_object_id() function to get current category id.
// Usage in archive or category (taxonomy) template $term_id = get_queried_object_id(); echo get_term_meta( $term_id, 'test_meta_field', true );
Changelog
Since 4.4.0 | Introduced. |
get_term_meta() get term meta code WP 6.8.1
function get_term_meta( $term_id, $key = '', $single = false ) { return get_metadata( 'term', $term_id, $key, $single ); }