[WooCommerce] 手動新增物流 Shipping Line item 項目在訂單的方法

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


最近在客製化一個客戶 WooCoomerce 網站的結帳欄位時,發現如果沒有需要使用到「運送」區塊的結帳表單,又或是把運送的結帳表單精簡到只有客製化欄位的這種情境。那訂單裡就不會出現「物流」運送相關資訊。

滿符合邏輯的沒錯,但如果只是希望節省填表單的繁瑣而使用了設定裡的「強制運送至客戶帳單地址」功能的話,那物流功能就會完全失效。

這些最直接的衝擊就是沒有辦法記錄到物流資訊,哪怕前端好像還是有可以讓你選像是超商取貨這類的功能。

所以如果有這需求,又要程式邏輯判斷下「自動」的補上物流資訊就需要寫程式來自己補:

function mxp_ecpay_cvs_shipping_hack($order, $data) {
    if (isset($data['CVSStoreID']) && $data['CVSStoreID'] != '') {
        $order->set_shipping_last_name($order->get_billing_last_name());
        $order->set_shipping_first_name($order->get_billing_first_name());
        $items = (array) $order->get_items('shipping');
        $calculate_tax_for = array(
            'country'  => 'TW',
            'state'    => '', 
            'postcode' => '', 
            'city'     => '', 
        );
        if (sizeof($items) == 0) {
            $item     = new WC_Order_Item_Shipping();
            $items    = array($item);
            $new_item = true;
        }
        foreach ($items as $item) {
            $item->set_method_title(__("711超商取貨"));
            $item->set_method_id($data['shipping_method'][0]);
            $item->calculate_taxes($calculate_tax_for);
            if (isset($new_item) && $new_item) {
                $order->add_item($item);
            } else {
                $item->save();
            }
        }
        $order->calculate_totals();
        $order->save();
    }
}
add_action('woocommerce_checkout_create_order', 'mxp_ecpay_cvs_shipping_hack', 21, 2);

上面程式碼片段這邊是以 RY 綠界超取 外掛 為例。

客製化過的結帳夜欄位讓前端還可以選擇超商,但卻無法觸發取得超商物流單的原因就是物流資訊的運費方案沒有寫回訂單裡。

所以透過 woocommerce_checkout_create_order 這個勾點來介入,讓產生訂單資訊之前可以先補上物流資訊。

關鍵字是「WC_Order_Item_Shipping」,補上物流運送資訊的訂單要取出這個資訊就是 $order->get_items( 'shipping' ); 方法。


Share:

作者: Chun

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

發佈留言

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


文章
Filter
Apply Filters
Mastodon