【问题标题】:Get parent category for CPT获取 CPT 的父类别
【发布时间】:2020-03-30 08:25:12
【问题描述】:

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

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

谁能帮忙?

【问题讨论】:

    标签: wordpress categories


    【解决方案1】:

    您可以使用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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      相关资源
      最近更新 更多