本篇文章更新時間:2020/05/08
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣新台幣 贊助支持。


之前寫過新增可排序的後台欄位 Admin Column 的運用, [WordPress] 客製化內容類型中設定可排序欄位(Sortable columns) 這就是把原本的欄位補上可排序的功能。但如果內建的欄位不見了,想補上怎麼辦?

CPT Category

圖中這個分類顯示功能很常見,但如果今天碰到沒開啟的話,可以在子主題裡補上:

function mxp_add_faq_cat_column() {
    register_taxonomy(
        'faq_cat',
        'faq',
        array(
            'labels'            => array(
                'name'              => '服務說明分類',
                'singular_name'     => '服務說明分類',
                'search_items'      => '搜尋分類',
                'all_items'         => '全部分類',
                'parent_item'       => '上層分類',
                'parent_item_colon' => '上層分類:',
                'edit_item'         => '編輯分類',
                'update_item'       => '更新分類',
                'add_new_item'      => '新增分類',
                'new_item_name'     => '新分類名',
                'menu_name'         => '服務說明分類',
            ),
            'show_ui'           => true,
            'show_admin_column' => true,
        )
    );
}
add_action('init', 'mxp_add_faq_cat_column');

主要就是使用 register_taxonomy 方法在 init 的 Hook 把方法補完。

而在後台列表中呼叫出分類欄位的參數是: show_admin_column,記得設定為 true 就會出現。

分類的功能還會出現在修改內容的內頁側邊,尤其 WordPress 第五版後多了 Gutenberg 編輯器 為預設後,如果沒出現分類的功能則是要記得 show_in_rest 這個參數也要設定為 true,才會出現哦。

完整的把分類功能加入客製化內容類型 Custom Post Type 的 code 如下:

function mxp_add_faq_cat_column() {
    register_taxonomy(
        'faq_cat',//Taxonomy Slug
        'faq', //Post Type Slug
        array(
            'hierarchical'      => true,
            'labels'            => array(
                'name'              => '服務說明分類',
                'singular_name'     => '服務說明分類',
                'search_items'      => '搜尋分類',
                'all_items'         => '全部分類',
                'parent_item'       => '上層分類',
                'parent_item_colon' => '上層分類:',
                'edit_item'         => '編輯分類',
                'update_item'       => '更新分類',
                'add_new_item'      => '新增分類',
                'new_item_name'     => '新分類名',
                'menu_name'         => '服務說明分類',
            ),
            'show_ui'           => true,
            'show_in_rest'      => true,
            'show_admin_column' => true,
            'query_var'         => true,
        )
    );
}
add_action('init', 'mxp_add_faq_cat_column');

後記

文件中寫的 hierarchical 是一個很有意思的參數,他的作用是在網址結構上,設定是否接受多層架構,還是要扁平化的網址。

看下方範例就知道差異,看用法,其實也無好壞之分,至於有沒有 SEO 的考量,可以參考看看這篇: Flat vs Hierarchical URL Structure

階層結構:

  • https://www.mxp.tw/階層一
  • https://www.mxp.tw/階層一/階層二/

扁平結構:

  • https://www.mxp.tw/階層一
  • https://www.mxp.tw/階層二

想對 Custom Post Type 這個 WordPress 核心架構多了解的話,也非常推薦從 Custom Post Type UI 這款外掛下手,裡面有對各項參數的簡介,玩的時候可以輕鬆透過介面改參數來測試。


Share:

作者: Chun

資訊愛好人士。主張「人人都該為了偷懶而進步」。期許自己成為斜槓到變進度條 100% 的年輕人。[///////////____36%_________]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


文章
Filter
Apply Filters
Mastodon