首页 > 解决方案 > 获取 CPT 的父类别

问题描述

我正在处理一个索引页面,其中列出了自定义帖子类型的所有帖子。我一直在使用<?php echo strip_tags(get_the_term_list( $post->ID, 'genre', ' ',' &#8226; ')); ?>.

我们需要添加子类别,但我不希望这些显示在索引页面上 - 只是父类别。已尝试使用get_term_parents_list此处的其他一些示例,但无法正常工作。

任何人都可以帮忙吗?

标签: wordpresscategories

解决方案


您可以使用get_the_terms过滤器更改要返回的条款。

add_filter('get_the_terms', 'only_parent_genre', 10, 3);
function only_parent_genre($terms, $post_id, $taxonomy) {

    // TODO for you : Add condition to heck if you are not on your custom index too.
    if(is_admin() || $taxonomy !== 'genre') {
        return $terms;
    }

    // Loop over terms and if parent is something different than 0, it means that's its a child term
    foreach($terms as $key => $term) {
        if($term->parent !== 0) {
            unset($terms[$key]);
        }
    }

    return $terms;
}

推荐阅读