[WooCommerce] 給商品增加客製化分類選項的方法

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


這需求不算少見,像是商品來源廠商、商品某些專有品牌屬性等。內建的功能算滿方便了,但總有客製化的需求存在,剛好這次就是「廠商」。

// 註冊廠商分類 Taxonomy
function mxp_register_vendor_taxonomy() {
    $labels = [
        "name"          => "廠商",
        "singular_name" => "廠商",
        "menu_name"     => "廠商",
        "all_items"     => "廠商",
        "edit_item"     => "編輯廠商分類",
        "view_item"     => "查看廠商分類",
        "update_item"   => "更新廠商",
        "add_new_item"  => "新增廠商",
        "new_item_name" => "廠商",
        "search_items"  => "搜尋廠商",
    ];

    $args = [
        "label"                 => "廠商",
        "labels"                => $labels,
        "public"                => true,
        "publicly_queryable"    => true,
        "hierarchical"          => true, //有階層是「分類」,沒階層是「標籤」
        "show_ui"               => true,
        "show_in_menu"          => true,
        "show_in_nav_menus"     => true,
        "query_var"             => true,
        "rewrite"               => ['slug' => 'mxp-vendor', 'with_front' => true],
        "show_admin_column"     => false,
        "show_in_rest"          => true,
        "show_tagcloud"         => false,
        "rest_base"             => "mxp_vendor",
        "rest_controller_class" => "WP_REST_Terms_Controller",
        "rest_namespace"        => "wp/v2",
        "show_in_quick_edit"    => true,
        "sort"                  => true,
        "show_in_graphql"       => false,
    ];
    register_taxonomy("mxp_vendor", ["product"], $args);
}
add_action('woocommerce_init', 'mxp_register_vendor_taxonomy');

這邊註冊「廠商」分類的時機(勾)點在 woocommerce_init WooCommerce 初始化後,再來是註冊在「product」這個產品內容類型,分類頁面的路徑是 Slug「mxp-vendor」。

如此就可以在後台針對商品開始指定廠商分類。

而前端部分要注意兩個地方:

  1. 主題有沒有宣告支援 WooCommerce。

    // 讓主題支援使用 WC 的方法
    if (class_exists('WooCommerce')) {
        add_theme_support('woocommerce');
        add_theme_support('wc-product-gallery-zoom');
        add_theme_support('wc-product-gallery-lightbox');
        add_theme_support('wc-product-gallery-slider');
    }

    直接寫在(子)主題中,或是註冊 after_setup_theme 這個勾點就可以宣告支援。

  2. 如果指派了商品到這個廠商分類,但點了分類頁的連結 /mxp-vendor/xxx 會 404 找不到頁面,記得可以先去「設定」中找到「永久連結」,重新儲存一次!

(子)主題內會依照主題架構圖 Template Hierarchytaxonomy 路徑走。也就是可以使用 taxonomy-mxp_vendor.php 或是最根部的 taxonomy.php 來處理,建議是前者指定分類 Slug 形式來處理較有彈性。

檔案範例也很簡單,可以直接引用 WooCommerce 既有的集合頁面範例:

這個類型的開發主題網路上搜尋得到的答案都比較偏向 WordPress 本來的處理方式,也是多找了幾個參考資料才有特別提到 WooCommerce 有加入對主題支援度的部分可以運用。


Share:

作者: Chun

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

發佈留言

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


文章
Filter
Apply Filters
Mastodon