Using WordPress ‘get_terms()’ PHP function

The get_terms() WordPress PHP function retrieves the terms in a given taxonomy or list of taxonomies.

Usage

$terms = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => false,
) );

Parameters

  • taxonomy (string|array) – Taxonomy name, or array of taxonomy names, to which results should be limited.
  • object_ids (int|array) – Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
  • orderby (string) – Field(s) to order terms by.
  • order (string) – Whether to order terms in ascending or descending order. Accepts ‘ASC’ (ascending) or ‘DESC’ (descending). Default ‘ASC’.
  • hide_empty (bool|int) – Whether to hide terms not assigned to any posts. Accepts 1|true or 0|false. Default 1|true.
  • include (int|string) – Array or comma/space-separated string of term IDs to include. Default empty array.
  • exclude (int|string) – Array or comma/space-separated string of term IDs to exclude. If $include is non-empty, $exclude is ignored. Default empty array.
  • exclude_tree (int|string) – Array or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If $include is non-empty, $exclude_tree is ignored.

More information

See WordPress Developer Resources: get_terms()

Examples

Get all categories

Get all categories without hiding empty ones.

$categories = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => false,
) );

Get terms from multiple taxonomies

Get all terms from both ‘category’ and ‘post_tag’ taxonomies.

$terms = get_terms( array(
    'taxonomy' => array('category', 'post_tag'),
    'hide_empty' => false,
) );

Get terms ordered by post count

Get all terms from ‘category’ taxonomy ordered by the number of associated posts.

$terms = get_terms( array(
    'taxonomy' => 'category',
    'orderby' => 'count',
    'order' => 'DESC',
) );

Include specific terms

Get all terms from ‘category’ taxonomy including only specific term IDs.

$terms = get_terms( array(
    'taxonomy' => 'category',
    'include' => array(12, 34, 56),
) );

Exclude specific terms

Get all terms from ‘category’ taxonomy excluding specific term IDs and their descendants.

$terms = get_terms( array(
    'taxonomy' => 'category',
    'exclude_tree' => array(12, 34, 56),
) );