WooCommerce 自定義功能:不同溫層商品無法同時結帳(分溫層結帳)

在使用 WooCommerce 建立網路商店時,我們經常需要根據不同的業務需求進行自定義功能開發。以下是介紹如何實現「不同溫層商品無法同時結帳」的自定義功能,確保不同溫層的商品在運送過程中保持其品質。

功能說明

我們實現了三個主要功能:

  1. 在購物車中檢查並提示不同溫層商品無法同時結帳。
  2. 禁用結帳按鈕,直到購物車中的商品調整為同一溫層。
  3. 在購物車中顯示每件商品的運送類別。

以下是每個功能的實現代碼及其解說。

檢查並顯示通知

首先,我們需要在購物車檢查階段檢查不同溫層的商品,並顯示錯誤通知。

function custom_shipping_class_notice() {
    // 獲取購物車內容
    $cart = WC()->cart->get_cart();

    $shipping_classes = array();
    foreach ($cart as $cart_item) {
        $product = wc_get_product($cart_item['product_id']);
        $shipping_class = $product->get_shipping_class();
        
        if (!empty($shipping_class)) {
            $shipping_classes[] = $shipping_class;
        }
    }

    // 移除重複值和空值
    $shipping_classes = array_filter(array_unique($shipping_classes));

    if (count($shipping_classes) > 1) {
        wc_print_notice(__('不同溫層商品不可同時結帳', 'woocommerce'), 'error');
    }
}
add_action('woocommerce_check_cart_items', 'custom_shipping_class_notice');

此函數 custom_shipping_class_notice 在檢查購物車時執行,會檢查購物車中商品的運送類別,並在檢測到多於一個運送類別時顯示錯誤通知。

禁用結帳按鈕

接下來,我們需要在有不同溫層商品時禁用結帳按鈕。

function disable_checkout_button() {
    // 獲取購物車內容
    $cart = WC()->cart->get_cart();

    $shipping_classes = array();
    foreach ($cart as $cart_item) {
        $product = wc_get_product($cart_item['product_id']);
        $shipping_class = $product->get_shipping_class();

        if (!empty($shipping_class)) {
            $shipping_classes[] = $shipping_class;
        }
    }

    // 移除重複值和空值
    $shipping_classes = array_filter(array_unique($shipping_classes));

    if (count($shipping_classes) > 1) {
        remove_action('woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20);
    }
}
add_action('woocommerce_proceed_to_checkout', 'disable_checkout_button');

函數 disable_checkout_button 在購物車頁面上執行,會檢查購物車中商品的運送類別,並在檢測到多於一個運送類別時禁用結帳按鈕。

在購物車中顯示運送類別

最後,我們在購物車中顯示每件商品的運送類別,方便用戶查看和管理。





function display_shipping_class_in_cart($item_name, $cart_item, $cart_item_key) {
    $product = wc_get_product($cart_item['product_id']);
    $shipping_class = $product->get_shipping_class();

    if (!empty($shipping_class)) {
        $shipping_class_name = get_term_by('slug', $shipping_class, 'product_shipping_class')->name;
        $item_name .= ' (' . $shipping_class_name . ')';
    }

    return $item_name;
}
add_filter('woocommerce_cart_item_name', 'display_shipping_class_in_cart', 10, 3);

此函數 display_shipping_class_in_cart 會在購物車中顯示每件商品的運送類別名稱,便於顧客了解每件商品的運送需求。

總結

通過以上三個功能,我們實現了 WooCommerce 購物車中不同溫層商品無法同時結帳的需求。這不僅保證了商品在運送過程中的品質,還提升了顧客的購物體驗。如果您有類似的需求,可以參考這些代碼進行自定義開發,滿足業務需求。

瀏覽次數:49