get_terms( array|string $args = array(), array $deprecated = '' )

Retrieve the terms in a given taxonomy or list of taxonomies.


Description Description

You can fully inject any customizations to the query before it is sent, as well as control the output with a filter.

The ‘get_terms’ filter will be called when the cache has the term and will pass the found term along with the array of $taxonomies and array of $args. This filter is also called before the array of terms is passed and will pass the array of terms, along with the $taxonomies and $args.

The ‘list_terms_exclusions’ filter passes the compiled exclusions along with the $args.

The ‘get_terms_orderby’ filter passes the ORDER BY clause for the query along with the $args array.

Prior to 4.5.0, the first parameter of get_terms() was a taxonomy or list of taxonomies:

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

Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array:

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

Parameters Parameters

$args

(array|string) (Optional) Array or string of arguments to get terms.

  • 'taxonomy'
    (string|array) Taxonomy name, or array of taxonomies, to which results should be limited.
  • 'orderby'
    (string) Field(s) to order terms by. Accepts term fields ('name', 'slug', 'term_group', 'term_id', 'id', 'description'), 'count' for term taxonomy count, 'include' to match the 'order' of the $include param, 'meta_value', 'meta_value_num', the value of $meta_key, the array keys of $meta_query, or 'none' to omit the ORDER BY clause. Defaults to 'name'.
  • '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'
    (array|string) Array or comma/space-separated string of term ids to include.
  • 'exclude'
    (array|string) Array or comma/space-separated string of term ids to exclude. If $include is non-empty, $exclude is ignored.
  • 'exclude_tree'
    (array|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.
  • 'number'
    (int|string) Maximum number of terms to return. Accepts ''|0 (all) or any positive number. Default ''|0 (all).
  • 'offset'
    (int) The number by which to offset the terms query.
  • 'fields'
    (string) Term fields to query for. Accepts 'all' (returns an array of complete term objects), 'ids' (returns an array of ids), 'id=>parent' (returns an associative array with ids as keys, parent term IDs as values), 'names' (returns an array of term names), 'count' (returns the number of matching terms), 'id=>name' (returns an associative array with ids as keys, term names as values), or 'id=>slug' (returns an associative array with ids as keys, term slugs as values). Default 'all'.
  • 'name'
    (string|array) Optional. Name or array of names to return term(s) for.
  • 'slug'
    (string|array) Optional. Slug or array of slugs to return term(s) for.
  • 'hierarchical'
    (bool) Whether to include terms that have non-empty descendants (even if $hide_empty is set to true). Default true.
  • 'search'
    (string) Search criteria to match terms. Will be SQL-formatted with wildcards before and after.
  • 'name__like'
    (string) Retrieve terms with criteria by which a term is LIKE $name__like.
  • 'description__like'
    (string) Retrieve terms where the description is LIKE $description__like.
  • 'pad_counts'
    (bool) Whether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
  • 'get'
    (string) Whether to return terms regardless of ancestry or whether the terms are empty. Accepts 'all' or empty (disabled).
  • 'child_of'
    (int) Term ID to retrieve child terms of. If multiple taxonomies are passed, $child_of is ignored. Default 0.
  • 'parent'
    (int|string) Parent term ID to retrieve direct-child terms of.
  • 'childless'
    (bool) True to limit results to terms that have no children. This parameter has no effect on non-hierarchical taxonomies. Default false.
  • 'cache_domain'
    (string) Unique cache key to be produced when this query is stored in an object cache. Default is 'core'.
  • 'update_term_meta_cache'
    (bool) Whether to prime meta caches for matched terms. Default true.
  • 'meta_query'
    (array) Meta query clauses to limit retrieved terms by. See WP_Meta_Query.
  • 'meta_key'
    (string) Limit terms to those matching a specific metadata key. Can be used in conjunction with $meta_value.
  • 'meta_value'
    (string) Limit terms to those matching a specific metadata value. Usually used in conjunction with $meta_key.

Default value: array()

$deprecated

(array) (Optional) Argument array, when using the legacy function parameter format. If present, this parameter will be interpreted as $args, and the first function parameter will be parsed as a taxonomy or array of taxonomies.

Default value: ''


Top ↑

Return Return

(array|int|WP_Error) List of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies do not exist.


Top ↑

Source Source

File: wp-includes/taxonomy.php

function get_terms( $args = array(), $deprecated = '' ) {
	global $wpdb;

	$term_query = new WP_Term_Query();

	/*
	 * Legacy argument format ($taxonomy, $args) takes precedence.
	 *
	 * We detect legacy argument format by checking if
	 * (a) a second non-empty parameter is passed, or
	 * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
	 */
	$_args = wp_parse_args( $args );
	$key_intersect  = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
	$do_legacy_args = $deprecated || empty( $key_intersect );

	if ( $do_legacy_args ) {
		$taxonomies = (array) $args;
		$args = wp_parse_args( $deprecated );
		$args['taxonomy'] = $taxonomies;
	} else {
		$args = wp_parse_args( $args );
		if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
			$args['taxonomy'] = (array) $args['taxonomy'];
		}
	}

	if ( ! empty( $args['taxonomy'] ) ) {
		foreach ( $args['taxonomy'] as $taxonomy ) {
			if ( ! taxonomy_exists( $taxonomy ) ) {
				return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
			}
		}
	}

	$terms = $term_query->query( $args );

	// Count queries are not filtered, for legacy reasons.
	if ( ! is_array( $terms ) ) {
		return $terms;
	}

	/**
	 * Filters the found terms.
	 *
	 * @since 2.3.0
	 * @since 4.6.0 Added the `$term_query` parameter.
	 *
	 * @param array         $terms      Array of found terms.
	 * @param array         $taxonomies An array of taxonomies.
	 * @param array         $args       An array of get_terms() arguments.
	 * @param WP_Term_Query $term_query The WP_Term_Query object.
	 */
	return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.5.0 Changed the function signature so that the $args array can be provided as the first parameter. Introduced 'meta_key' and 'meta_value' parameters. Introduced the ability to order results by metadata.
4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the orderby parameter. Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return a list of WP_Term objects.
4.2.0 Introduced 'name' and 'childless' parameters.
2.3.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by ancawonka

    As of WordPress 4.6.1, here’s the array that’s returned (to add to Leo’s helpful note above)

    array(1) {
      [0]=>
      object(WP_Term) (11) {
        ["term_id"]=>  //int
        ["name"]=>	//string 
        ["slug"]=>  //string 
        ["term_group"]=>  //int
        ["term_taxonomy_id"]=> //int
        ["taxonomy"]=>	//string
        ["description"]=>	//string
        ["parent"]=>	//int
        ["count"]=>	// int
        ["filter"]=>	//string
        ["meta"]=> array(0) { // presumably this would be some returned meta-data?
        }
      }
    }
    
  2. Skip to note content
    Contributed by znowebdev

    Get all post categories ordered by count.

    String syntax:

    $categories = get_terms( 'category', 'orderby=count&hide_empty=0' );
    

    Array syntax:

    $categories = get_terms( 'category', array(
    	'orderby'    => 'count',
    	'hide_empty' => 0,
    ) );
    

    Get all the links categories:

    $my_links_categories = get_terms( 'link_category', 'orderby=count&hide_empty=0' );
    

    List all the terms in a custom taxonomy, without a link:

    $terms = get_terms( 'my_taxonomy' );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    	echo '<ul>';
    	foreach ( $terms as $term ) {
    		echo '<li>' . $term->name . '</li>';
    	}
    	echo '</ul>';
    }
    

    List all the terms, with link to term archive, separated by an interpunct (ยท):

    $args = array( 'hide_empty=0' );
    
    $terms = get_terms( 'my_term', $args );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
    	$count = count( $terms );
    	$i = 0;
    	$term_list = '<p class="my_term-archive">';
    	foreach ( $terms as $term ) {
    		$i++;
    		$term_list .= '<a href="' . esc_url( get_term_link( $term ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) ) . '">' . $term->name . '</a>';
    		if ( $count != $i ) {
    			$term_list .= ' &middot; ';
    		}
    		else {
    			$term_list .= '</p>';
    		}
    	}
    	echo $term_list;
    }
    
  3. Skip to note content
    Contributed by Khoi Nguyen

    Get Categories by custom post type with dropdown:

    function taxonomy_list_dropdown($type, $post_type) {
      $terms = get_terms($type);
      $category = taxonomy_current($type);
    
      if ( !empty( $terms ) && !is_wp_error( $terms ) ){
        the_terms_list(
          'categories__dropdown icon-dropdown',
          array(
            'show_option_all'  => 'Click to filter',
            'taxonomy'         => $type,
            'current_category' => $category->term_id,
            'value_field'      => 'slug',
            'selected'         => $category->slug,
          ),
          'dropdown',
          'data-module-init="redirect-dropdown"'
        );
      }
    }
    

You must log in before being able to contribute a note or feedback.