我已经创建了自定义的post类型和4个分类。第一、第二和第三种分类法是等级化的,最后一种则不是。是否有可能在不使用名称的情况下显示分层次和非分级分类法?
为了更好的理解: CPT有4个分类。1、2和3是分层的,4种是非层次的.现在,在span#one中,我希望显示所有层次术语,在span#two中,显示所有特定帖子的非层次术语。
我怎么能这么做?
发布于 2019-05-15 08:43:40
在开始时,使用get_object_taxonomies()为给定类型的post注册分类法。然后检查哪些是分层的,例如使用is_taxonomy_hierarchical() 条件标签。最后一步是显示列表。
// 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 '';
foreach ( $terms_tree as $links ) {
echo $links;
}
echo '';或者:
//
// 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 '';
foreach ( $terms_tree as $term ) {
$link = get_term_link( $term );
if ( is_wp_error( $link ) ) {
continue;
}
echo '' . $term->name . ' ';
}
echo '';
// the same with $terms_flat第二个解决方案(使用get_terms)按名称排序术语from所有层次分类法,而第一个解决方案(使用get_the_term_list)排序术语from --每个层次分类法分别。
参考文献:
https://wordpress.stackexchange.com/questions/337926
复制相似问题