为了账号安全,请及时绑定邮箱和手机立即绑定

如何在页面上仅显示特定类别标签/名称并隐藏其他类别名称?

如何在页面上仅显示特定类别标签/名称并隐藏其他类别名称?

PHP
人到中年有点甜 2023-06-30 16:23:30
我试图仅显示 1 个类别名称,并希望在帖子列表页面中隐藏其他类别名称。add_filter('get_the_terms', 'hide_categories_terms', 10, 3);function hide_categories_terms($terms, $post_id, $taxonomy){$excludeIDs = array(1,322,320,321);// get all the terms $exclude = array();foreach ($excludeIDs as $id) {    $exclude[] = get_term_by('id', $id, 'category');}// filter the categoriesif (!is_admin()) {    foreach($terms as $key => $term){        if($term->taxonomy == "category"){            foreach ($exclude as $exKey => $exTerm) {                if($term->term_id == $exTerm->term_id) unset($terms[$key]);            }        }    }}return $terms;它隐藏了所有类别名称,但不显示我想要显示的类别名称。请帮助我
查看完整描述

1 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

您应该能够做到这一点,而无需获取排除项或双循环:


add_filter('get_the_terms', 'hide_categories_terms', 10, 3);

function hide_categories_terms($terms, $post_id, $taxonomy){

    

    if ( ! is_admin() && is_single() ) {

        // filter for terms that are not in the exclude array

        $filtered_terms = array_filter($terms, function($term) {

            $excludeIDs = array(1, 322, 320, 321);

            return ! in_array($term->term_id, $excludeIDs);

        });


        // return filtered array of terms

        return $filtered_terms;

    }


    // return default terms JIC the above case is not met

    return $terms;

}

如果您运行的是 PHP 7.4+,您可以通过另一种方式编写此代码以节省一些行:


add_filter('get_the_terms', 'hide_categories_terms', 10, 3);

function hide_categories_terms($terms, $post_id, $taxonomy){

    

    if ( ! is_admin() && is_single() ) {

        $excludeIDs = [1, 322, 320, 321];

        // filter for terms that are not in the exclude array

        $filtered_terms = array_filter($terms, fn($t) => ! in_array($t->term_id, $excludeIDs));


        // return filtered array of terms

        return $filtered_terms;

    }


    // return default terms JIC the above case is not met

    return $terms;

}


查看完整回答
反对 回复 2023-06-30
  • 1 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号