Using WordPress ‘get_term_by()’ PHP function

The get_term_by() WordPress PHP function retrieves all term data from the database based on a specified term field and data.

Usage

get_term_by($field, $value, $taxonomy, $output, $filter);

Parameters

  • $field (string): Required. Either ‘slug’, ‘name’, ‘term_id’ (or ‘id’, ‘ID’), or ‘term_taxonomy_id’.
  • $value (string|int): Required. Search for this term value.
  • $taxonomy (string): Optional. Taxonomy name. Optional, if $field is ‘term_taxonomy_id’. Default: ”.
  • $output (string): Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively. Default: OBJECT.
  • $filter (string): Optional. How to sanitize term fields. Default ‘raw’. Default: ‘raw’.

More information

See WordPress Developer Resources: get_term_by

Examples

Get term by name in Categories taxonomy

$category = get_term_by('name', 'news', 'category');

Get term by name in Tags taxonomy

$tag = get_term_by('name', 'news', 'post_tag');

Get term by name in a Custom taxonomy

$term = get_term_by('name', 'news', 'my_custom_taxonomy');

Get term by name from theme’s nav menus

$menu = get_term_by('name', 'Default Menu', 'nav_menu');

Get term by ID in Categories taxonomy

get_term_by('id', 12, 'category');