get_terms是wordpress里获取分类法的一个函数,一般用于获取自定义分类法(不是默认的文章分类与标签哦,虽然也可以通过这个函数来获取,但是有更专业的函数来获取文章分类与标签)。

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

该函数有两个参数,第一个一般传分类法的名称slug,比如post_tag就表示文章标签,或者是自定义的分类法例如topic可能就表示专题。第二个参数就是获取条件,比如显示个数、是否显示空值。

也可以只传第一个参数,那么就是传一个数组,其实就是把两个参数合成一个参数,把第一个参数的名称slug加到第二个参数的数组里。

例如:

$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'=> '',
);

一般的自定义分类法的用法如下:

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