亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在頁面上僅顯示特定類別標簽/名稱并隱藏其他類別名稱?

如何在頁面上僅顯示特定類別標簽/名稱并隱藏其他類別名稱?

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 關注
  • 140 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號