WordPress get_terms()的使用方法:
例1.输出term相关信息
<ul class="products"> <?php $terms = get_terms('category',array( 'with_thumbnail' => true, 'hide_empty' => false, ) ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) {?> <li> <a href="<?php echo get_term_link($term->term_id) ?>"> <div class="term-pic"> <?php the_term_thumbnail($term ->term_id, 'post-thumbnail');?> </div> <div> <h3> <?php echo $term->name;?> </h3> <div> <?php echo $term->description;?> </div> </div> </a> </li> <?php } }?> </ul>
例2.循环term显示相应的文章
<?php $terms = get_terms([ 'taxonomy' => 'area', 'hide_empty' => true, ]); foreach( $terms as $term):?> <div class="area-part"> <h3> <?php echo $term->name; ?> </h3> <ul class="posts-list"> <?php $args = array( 'post_type'=>'store', 'tax_query' => array( array( 'taxonomy' => 'area', 'field' => 'id', 'terms' => $term->term_id, ), ), ); $query = new WP_Query( $args ); if( $query->have_posts()): while($query->have_posts()):$query->the_post(); get_template_part('partials/content','shopList'); //Restore orginial post Data wp_reset_postdata(); endwhile;?> </ul> <?php endif;?> </div> <?php endforeach; ?>
其他
get_terms()默认参数:
$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_terms()数组返回值:
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? } } }