亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 WC_Shipping_Methodcalculate_shipping()

如何在 WC_Shipping_Methodcalculate_shipping()

PHP
慕神8447489 2023-10-15 17:16:20
因此,我試圖創建一種 woocommerce 運輸方法,該方法采用購物車小計并按用戶定義的購物車小計百分比收取運費。作為實現這個目標的第一步,我所做的基本上是這樣的class Subtotal_Percentage_Method extends WC_Shipping_Method {    // to store percentage    private $percentage_rate    // constructor that handles settings    // here is where i start calculation    public function calculate_shipping($packages = array()) {        $cost = $this->percentage_rate * 1000;        add_rate(array(            'id' => $this->id,            'label' => $this->title,            'cost' => $cost        ));    }}這個有效。但是,當我更改calculate_shipping方法以在計算中使用購物車小計時,它不起作用public function calculate_shipping($packages = array()) {    $subtotal = WC()->cart->subtotal;    $cost = $subtotal * $this->percentage_rate / 100;    add_rate(array(        'id' => $this->id,        'label' => $this->title,        'cost' => $cost    ));}誰能告訴我我做錯了什么?
查看完整描述

1 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

由于這與運輸包裹有關(因為購物車商品可以拆分(劃分)為多個運輸包裹),因此您需要使用方法$packages中包含的變量參數calculate_shipping()。


WC_Cart因此,如果不使用對象方法,您的代碼將會略有不同:


public function calculate_shipping( $packages = array() ) {

    $total = $total_tax = 0; // Initializing


    // Loop through shipping packages

    foreach( $packages as $key => $package ){

            // Loop through cart items for this package

        foreach( $package['contents'] as $item ){

            $total      += $item['total']; // Item subtotal discounted

            $total_tax  += $item['total_tax']; // Item subtotal tax discounted

        }

    }


    add_rate( array(

        'id'       => $this->id,

        'label'    => $this->title,

        'cost'     => $total * $this->percentage_rate / 100,

        // 'calc_tax' => 'per_item'

    ) );

}

代碼位于活動子主題(活動主題)的functions.php 文件中。經過測試并有效。


注:此處計算的是折扣后的購物車商品小計(不含稅)。您可以輕松添加添加使其在含稅折扣后的購物車商品小計中,替換:


'cost'     => $total * $this->percentage_rate / 100,

 

經過:


'cost'     => ($total + $total_tax) * $this->percentage_rate / 100,

您可以查看如何制作運輸包裹:
WC_Cart get_shipping_packages()方法源代碼

如果您還想處理傳送類等,請檢查:
WC_Shipping_Flat_Rate calculate_shipping()方法源代碼。


查看完整回答
反對 回復 2023-10-15
  • 1 回答
  • 0 關注
  • 105 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號