【问题标题】:How to get cart subtotal inside WC_Shipping_Method calculate_shipping() method如何在 WC_Shipping_Method calculate_shipping() 方法中获取购物车小计
【发布时间】:2020-08-18 21:34:36
【问题描述】:

因此,我尝试创建一种 woocommerce 运输方法,该方法采用购物车小计并收取用户定义的购物车小计百分比作为运费。作为朝着这个目标迈出的第一步,我做的ehat基本上是这样的

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
    ));
}

谁能告诉我我做错了什么?

【问题讨论】:

    标签: php wordpress woocommerce calculation shipping-method


    【解决方案1】:

    由于这与运输包裹有关(因为购物车物品可以拆分(划分)为多个运输包裹),您需要使用 calculate_shipping() 方法中包含的变量 $packages 参数。

    因此,如果不使用 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。

    【讨论】:

    • 您的代码是在折扣前还是折扣后得到价格?我想做的是打折后的价格。
    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2021-11-12
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多