get_term_field()
Gets the term field. The field is sanitized by the function sanitize_term_field().
The field is checked for existence before retrieval. The function is created for convenience of use in context.
Uses: sanitize_term_field()
Used By: term_description()
No Hooks.
Returns
String|Int|null|WP_Error. Returns an empty string if $term is not an object or if the field $field is not found on the term ($term).
Usage
get_term_field( $field, $term, $taxonomy, $context );
- $field(string) (required)
- The term field to retrieve.
- $term(number/object) (required)
- The term ID. Since version 4.4, a WP_Term object can be passed.
- $taxonomy(string)
- The name of the taxonomy. Since version 4.4, this parameter has become optional.
Default: '' - $context(string)
The type of filtering. One of the values:
raw- simply returns the valueedit- applies esc_html() filter if this field is description, and esc_attr() filter if it is another field.dbslugrssattribute- applies esc_attr() filterjs- applies esc_js() filter
Default: 'display'
Examples
#1 Display the description of category 34
The description is set in the admin when you create/modify a category. If there is no description, it will display the message "No description of the term was found".
$description = get_term_field( 'description', 34, 'category' );
if( is_wp_error( $description ) ){
echo 'No description of the term was found';
}
else {
echo $description;
}
Notes
Changelog
| Since 2.3.0 | Introduced. |
| Since 4.4.0 | The $taxonomy parameter was made optional. $term can also now accept a WP_Term object. |
get_term_field() get term field code WP 6.9.1
function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
$term = get_term( $term, $taxonomy );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! is_object( $term ) ) {
return '';
}
if ( ! isset( $term->$field ) ) {
return '';
}
return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
}