本篇文章更新時間:2023/08/08
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知或向一介資男的 LINE 社群反應。
如果本站內容對你有幫助,歡迎贊助支持


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

// 註冊廠商分類 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 既有的集合頁面範例:

<?php
get_header();
if (is_woocommerce()) {
    wc_get_template('archive-product.php');
}
get_footer();

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


Share:

作者: Chun

WordPress 社群貢獻者、開源社群推廣者。專注於 WordPress 外掛開發、網站效能最佳化、伺服器管理,以及 iDempiere 開源 ERP 導入與客製開發。曾參與 WordCamp Taipei 等社群活動,GitHub Arctic Code Vault Contributor。提供資訊顧問、WordPress 開發教學、主機最佳化與企業 ERP 整合服務。

發佈留言

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


文章
Filter
Apply Filters
Mastodon