The get_term_field() WordPress PHP function retrieves a sanitized term field for a specified term.
Usage
get_term_field( $field, $term, $taxonomy, $context )
Example:
$term_name = get_term_field( 'name', 42, 'category', 'display' );
Parameters
- $field (string): Required. The term field to fetch.
- $term (int|WP_Term): Required. The term ID or term object.
- $taxonomy (string): Optional. The taxonomy name. Default: ” (empty string).
- $context (string): Optional. How to sanitize term fields. See
sanitize_term_field()
for available options. Accepts ‘raw’, ‘edit’, ‘db’, ‘display’, ‘rss’, ‘attribute’, or ‘js’. Default: ‘display’.
More information
See WordPress Developer Resources: get_term_field()
Examples
Fetch term name
Retrieve the name of a term by its ID.
$term_id = 42; $taxonomy = 'category'; $term_name = get_term_field( 'name', $term_id, $taxonomy );
Fetch term description
Retrieve the description of a term using its term object.
$term_object = get_term_by( 'slug', 'travel', 'category' ); $term_description = get_term_field( 'description', $term_object );
Fetch term slug
Retrieve the slug of a term by its ID and sanitize it for display.
$term_id = 24; $taxonomy = 'post_tag'; $term_slug = get_term_field( 'slug', $term_id, $taxonomy, 'display' );
Fetch term count
Retrieve the count of posts associated with a term.
$term_id = 12; $taxonomy = 'category'; $term_count = get_term_field( 'count', $term_id, $taxonomy );
Fetch term parent ID
Retrieve the parent term ID of a specified term.
$term_id = 5; $taxonomy = 'category'; $parent_term_id = get_term_field( 'parent', $term_id, $taxonomy );