如何在WC_Shipping_Methodcalculate_shipping方法中获取购物车小计

问题描述

因此,我尝试创建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,'cost' => $cost
    ));
}

有人可以告诉我我在做什么错吗?

解决方法

由于这与运输包裹有关(因为购物车物品可以拆分(分成多个运输包裹)),因此您需要使用$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() method source code

如果您还想处理运输类和其他类,请检查:
WC_Shipping_Flat_Rate calculate_shipping() method source code