如何显示层级和非层级分类?

时间:2019-05-15 作者:Piotr Milecki

我已经创建了自定义帖子类型和4个分类法。第一、第二和第三种分类学是分级的,第三种不是。是否有可能在不使用名称的情况下分别显示层次和非层次分类法?

为了更好地理解:CPT有4种分类法。1、2和3是分级的,4分类法是非分级的。现在,在span#one中,我想显示所有层次术语,在span#two中,显示特定帖子的所有非层次术语。

我该怎么做?

1 个回复
SO网友:nmr

首先,使用为给定类型的帖子注册分类法get_object_taxonomies(). 然后检查哪些是分层的,例如使用is_taxonomy_hierarchical() conditional tag. 最后一步是显示列表。

// current post ID
$post_id = get_the_ID();
// taxonomies registered for this type of posts
$taxonomies = get_object_taxonomies( get_post_type() );

$taxs_tree = [];   // hierarchical taxonomies
$taxs_flat = [];   // non-hierarchical taxonomies
foreach ( $taxonomies as $tax )
{
    if ( is_taxonomy_hierarchical( $tax ) )
        $taxs_tree[] = $tax;
    else
        $taxs_flat[] = $tax;
}
从每个分类中获取术语并显示它们。

// get terms as links
$terms_flat = $terms_tree = [];
foreach ( $taxs_tree as $tax ) {
    $terms_tree[] = get_the_term_list( $post_id, $tax );
}
foreach ( $taxs_flat as $tax ) {
    $terms_flat[] = get_the_term_list( $post_id, $tax );
}

echo \'<span id="one">\';
foreach ( $terms_tree as $links ) {
   echo $links;
}
echo \'</span>\';
或:

//
// terms assigned to post, ordered by name, from all hierarchical taxonomies
$args = [
   \'taxonomy\'   => $taxs_tree,   // here you can pass array of taxonomies
   \'object_ids\' => get_the_ID(), // get only terms assigned to this post (current post)
   //\'orderby.  => \'name\',       // default
];
$terms_tree = get_terms( $args ); // array of WP_term objects

//
// terms assigned to post, ordered by name, from all non-hierarchical taxonomies
$args[\'taxonomy\'] = $taxs_flat;
$terms_flat = get_terms( $args ); // array of WP_term objects

//
// display 
echo \'<span id="one">\';
foreach ( $terms_tree as $term ) {
    $link = get_term_link( $term );
    if ( is_wp_error( $link ) ) {
        continue;
    }
    echo \'<a href="\' . esc_url( $link ) . \'" rel="tag">\' . $term->name . \'</a> \';
}
echo \'</span>\';

// the same with $terms_flat
第二种解决方案(使用get_terms) 对术语排序from all 按名称划分的层次分类法,而第一个get_the_term_list) 对术语排序from each 层次分类法separately.

参考资料:

get\\u terms()-function, parameters

  • get_term_link()
  • get_the_term_list()
  • 相关推荐