返回介绍

get_terms()

发布于 2017-09-11 00:20:53 字数 16827 浏览 1136 评论 0 收藏 0

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

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


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,
) );

参数

$args

(string|array) (Optional) Array or string of arguments. See WP_Term_Query::__construct() for information on accepted arguments.

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: ''


返回值

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


源代码

File: wp-includes/taxonomy.php

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

	$term_query = new WP_Term_Query();

	$defaults = array(
		'suppress_filter' => false,
	);

	/*
	 * 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, $defaults );
		$args['taxonomy'] = $taxonomies;
	} else {
		$args = wp_parse_args( $args, $defaults );
		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.' ) );
			}
		}
	}

	// Don't pass suppress_filter to WP_Term_Query.
	$suppress_filter = $args['suppress_filter'];
	unset( $args['suppress_filter'] );

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

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

	if ( $suppress_filter ) {
		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 );
}

更新日志

Versiondescription
4.8.0Introduced 'suppress_filter' parameter.
4.5.0Changed 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.0Introduced 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.0Introduced 'name' and 'childless' parameters.
2.3.0Introduced.

相关函数

Uses

  • wp-includes/class-wp-term-query.php: WP_Term_Query::__construct()
  • wp-includes/l10n.php: __()
  • wp-includes/functions.php: wp_parse_args()
  • wp-includes/taxonomy.php: get_terms
  • wp-includes/taxonomy.php: taxonomy_exists()
  • wp-includes/plugin.php: apply_filters()
  • wp-includes/class-wp-error.php: WP_Error::__construct()
  • Show 2 more uses Hide more uses

Used By

  • wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php: WP_REST_Terms_Controller::get_items()
  • wp-includes/class-wp-term-query.php: WP_Term_Query::get_terms()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::search_available_items_query()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::load_available_items_query()
  • wp-admin/includes/export.php: export_wp()
  • wp-admin/includes/template.php: wp_terms_checklist()
  • wp-admin/includes/template.php: wp_popular_terms_checklist()
  • wp-admin/includes/template.php: wp_link_category_checklist()
  • wp-admin/includes/post.php: edit_post()
  • wp-admin/includes/ajax-actions.php: wp_ajax_get_tagcloud()
  • wp-admin/includes/ajax-actions.php: wp_ajax_ajax_tag_search()
  • wp-admin/includes/class-wp-terms-list-table.php: WP_Terms_List_Table::display_rows_or_placeholder()
  • wp-admin/includes/nav-menu.php: _wp_ajax_menu_quick_search()
  • wp-admin/includes/nav-menu.php: wp_nav_menu_item_taxonomy_meta_box()
  • wp-includes/class-walker-category.php: Walker_Category::start_el()
  • wp-includes/category-template.php: wp_tag_cloud()
  • wp-includes/category-template.php: wp_dropdown_categories()
  • wp-includes/category.php: get_tags()
  • wp-includes/deprecated.php: get_all_category_ids()
  • wp-includes/category.php: get_categories()
  • wp-includes/category.php: get_category_by_path()
  • wp-includes/widgets/class-wp-widget-links.php: WP_Widget_Links::form()
  • wp-includes/taxonomy.php: wp_get_object_terms()
  • wp-includes/taxonomy.php: wp_insert_term()
  • wp-includes/taxonomy.php: wp_count_terms()
  • wp-includes/taxonomy.php: get_term_by()
  • wp-includes/bookmark-template.php: wp_list_bookmarks()
  • wp-includes/nav-menu.php: wp_get_nav_menus()
  • wp-includes/nav-menu.php: wp_get_nav_menu_items()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::wp_getTerms()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::_insert_post()
  • Show 26 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 6You must log in to vote on the helpfulness of this note 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. 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
    ) );
    

    If parent => 0 is passed, only top-level terms will be returned

    
    $terms = get_terms( array( 
        'taxonomy' => 'tax_name',
        'parent'   => 0
    ) );
    

    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;
    }
    

    List terms limit to those matching a specific metadata key and metadata value

    
        $terms= get_terms( array(
            'taxonomy' => 'taxonomy name',
            'meta_key' => 'metadata key',
            'meta_value' => 'metadata value'
        ) );
    

    Get terms ordered by value of meta-key:

    $terms = get_terms(
        'taxonomy_name',
        array(
            'meta_key' => 'custom_meta_key',
            'orderby' => 'custom_meta_key'
        )
    );

    Get categories and subcategories by custom taxonomies:

    $taxonomies = get_terms( array(
    	'taxonomy' => 'taxonomy_name',
    	'hide_empty' => false
    ) );
    
    if ( !empty($taxonomies) ) :
    	$output = '<select>';
    	foreach( $taxonomies as $category ) {
    		if( $category->parent == 0 ) {
    			$output.= '<optgroup label="'. esc_attr( $category->name ) .'">';
    			foreach( $taxonomies as $subcategory ) {
    				if($subcategory->parent == $category->term_id) {
    				$output.= '<option value="'. esc_attr( $subcategory->term_id ) .'">
    					'. esc_html( $subcategory->name ) .'</option>';
    				}
    			}
    			$output.='</optgroup>';
    		}
    	}
    	$output.='</select>';
    	echo $output;
    endif;

    Get Terms filtered by first letter

    
    $authors = get_terms('book-authors', array('name__like' => $first_l));
    
    function custom_tax_query( $pieces, $taxonomies, $args ) {
      if ( 'book-authors' == $taxonomies[0] ) {
        $pieces['where'] = str_replace("LIKE '%", "LIKE '", $pieces['where']);
      }
    return $pieces;
    }
    

    Order by parent term ID – not documented, but also works.

    
    $categories = get_terms( 'category', array(
        'orderby'    => 'parent',
    ) );
    

    Working with Advanced Custom Fields (field type: Taxonomy, output: Object) for filtering taxonomies.

    Case: Create a filter with main categories defined by ACF field, and all another should belongs to *others*.

    Solution:

    
    // Define Featured Category IDs first
    $featured_category_ids = array();
    // It must be output WP_Object
    $featured_categories = get_field('main_category_filters');
    
    // Creating loop to insert IDs to array.
    foreach( $featured_categories as $cat ) {
    	$featured_category_ids[] = $cat->term_id;
    }
    
    // Now, if Featured Categories are match, add their IDs via 'exclude'
    if( $featured_categories ) {
    	$args = array(
    		'taxonomy' => 'event_cat',
    		'parent' => 0,
    		'exclude' => $featured_category_ids
    	);
    } else {
        // If no featured, just display all terms
    	$args = array(
    		'taxonomy' => 'event_cat',
    		'parent' => 0
    	);
    }
    
    // Starting query terms now
    $other_categories = get_terms($args);
    

    All get_terms attributes with default values:
    (I try default from this article and it didn’t work. This works.)

    $get_terms_default_attributes = array (
    			'taxonomy' => 'category', //empty string(''), false, 0 don't work, and return empty array
    			'orderby' => 'name',
    			'order' => 'ASC',
    			'hide_empty' => true, //can be 1, '1' too
    			'include' => 'all', //empty string(''), false, 0 don't work, and return empty array
    			'exclude' => 'all', //empty string(''), false, 0 don't work, and return empty array
    			'exclude_tree' => 'all', //empty string(''), false, 0 don't work, and return empty array
    			'number' => false, //can be 0, '0', '' too
    			'offset' => '',
    			'fields' => 'all',
    			'name' => '',
    			'slug' => '',
    			'hierarchical' => true, //can be 1, '1' too
    			'search' => '',
    			'name__like' => '',
    			'description__like' => '',
    			'pad_counts' => false, //can be 0, '0', '' too
    			'get' => '',
    			'child_of' => false, //can be 0, '0', '' too
    			'childless' => false,
    			'cache_domain' => 'core',
    			'update_term_meta_cache' => true, //can be 1, '1' too
    			'meta_query' => '',
    			'meta_key' => array(),
    			'meta_value'=> '',
    	);

    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"'
        );
      }
    }
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文