如何在页面上只显示特定类别 label/name 并隐藏其他类别名称?

How to display only specific category label/name on page and hide other categories name?

我试图只显示 1 个类别名称并想在 post 列表页面中隐藏其他类别名称。

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 categories
if (!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;

它隐藏了所有类别名称但没有显示我想显示的类别名称。请帮帮我

你应该可以做到这一点w/o必须得到排除条款或双循环:

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;
}