0

woocommerce 运输的内置选项可以为购物车中的产品数量设置费用。还可以选择按运输等级收费。但是我有数千种产品,需要为每种产品收费(每种产品不是产品数量)。

例如,购物车中有 2 个产品“苹果”和 23 个产品“橙子”。我需要对任意数量的苹果收取 10 美元的固定费用,对任意数量的橙子收取 10 美元的固定费用。我似乎在任何可用的插件中都找不到解决方案。他们都按数量收费,但不是这个。

4

1 回答 1

2

要按购物车中的行项目获取费用,它需要以下内容:

1)在 WooCommerce 设置 > 运输:为您的“统一费率”运输方式(并保存)设置 10 的成本。

2)添加到functions.php您的活动子主题(或活动主题)的文件,此代码:

add_filter( 'woocommerce_package_rates', 'shipping_cost_based_on_number_of_items', 10, 2 );
function shipping_cost_based_on_number_of_items( $rates, $package ) {
    $numer_of_items = (int) sizeof($package['contents']);

    // Loop through shipping rates
    foreach ( $rates as $rate_key => $rate ){
        // Targetting "Flat rate" shipping method
        if( 'flat_rate' === $rate->method_id ) {
            $has_taxes = false;

            // Set the new cost
            $rates[$rate_key]->cost = $rate->cost * $numer_of_items;

            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    // New tax calculated cost
                    $taxes[$key] = $tax * $numer_of_items;
                    $has_taxes = true;
                }
            }
            // Set new taxes cost
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
        }
    }
    return $rates;
}

刷新运输缓存:( 必需)

  1. 此代码已保存在活动主题的 function.php 文件中。
  2. 购物车是空的
  3. 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。

测试和工作。

于 2019-05-12T16:16:19.453 回答