php - 在 Woocommerce 中具有最大成本的基于累进数量的运输成本

标签 php wordpress woocommerce cart shipping-method

(如何)我可以在 WooCommerce 中为固定运费设置 max_fee?

将此添加到运输方式的固定费用设置中的成本字段有效:

(1 * [qty]) + [fee min_fee = "2,5"]

(即每个订单的运费 2.5 + 每件产品 1 欧元)-> 至少 3.5 并且每件产品增加 + 1。

但是,我想收取最低 3,50(1 件商品)和 4,50 最高(2 件或更多商品)的费用。 IE。从功能上讲,这个公式:(3,5 * [qty]) [fee **max_fee** = "4,5"]

这可能吗?/正确的语法是什么?我在任何地方都找不到这个。我只找到this reference ("add max_fee shortcode attribute for flat rate" / "allow max_fee in addition to min_fee in flat rate costs fields")这似乎表明已实现针对固定费用(百分比除外)的 max_fee 的功能请求。但我无法让它工作。

最佳答案

您不能使用可用设置来收取定义的可变运费:

  • 3,50 第一项
  • 4,50 超过一项(2 项或更多项)

因此您需要使用以下自定义 Hook 函数:

add_filter('woocommerce_package_rates', 'custom_shipping_costs', 10, 2 );
function custom_shipping_costs( $rates, $package ){
    // Get cart items count
    $items_count = WC()->cart->get_cart_contents_count();

    // Your cost settings
    $new_cost = $items_count > 1 ? 4.5 : 3.5;

    // Loop through shipping methods rates
    foreach ( $rates as $rate_key => $rate ){
        $has_taxes = false;

        // Targeting "Flat rate" shipping methods
        if ( 'flat_rate' === $rate->method_id ) {
            $default_cost = $rates[$rate_key]->cost;

            $rates[$rate_key]->cost = $new_cost;

            $rate_conversion = $new_cost / $default_cost;

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

代码进入您的事件子主题(或事件主题)的 function.php 文件。经过测试并有效。

Once the code is saved, go in your flat rate settings and set the rate cost to 1.00:

enter image description here

Now the shipping rate will change from 3.50 (for one item) to 4.50 (for more than one items)

关于php - 在 Woocommerce 中具有最大成本的基于累进数量的运输成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53960147/

相关文章:

php - 对连接中的选择结果进行计数

php - 从另一个对象获取调用者类实例

wordpress - 如何将 id 添加到可视化 Composer 中的元素

php - WooCommerce 自动将产品图片添加到图库(如果图库为空)

php - 如何防止 WooCommerce 中某些国家/地区的邮政编码/邮政编码字段被隐藏

php - 如何使用mysql查询我的表的所有值?

php - MySQL Join查询贷方余额

WordPress 循环显示限制帖子

css - Wordpress - 更改多个 Div 的背景颜色

php - 在 WooCommerce Order received 页面上的文本中添加客户电子邮件