php - 基于 Woocommerce 中的运输等级和最低金额的有条件免费送货
问题描述
在有关运输方法的 woocommerce 中,我试图拥有以下内容:
- 仅在购物车中的产品 A:设置为“免运费”
- 产品 B 仅在购物车中:设置:
- 如果产品 B 购买量小于 200,则统一费率金额为 15
- 如果产品 B 购买量达到 200 或更多,则免费送货。
- 产品 A + 产品 B 同时在购物车中:“免费送货”,没有任何数量限制。
我尝试过使用统一费率和运费等级,如果产品 A 和产品 B 在那里,那么如果购物车没有达到 200,则需要 15 运费。
任何帮助表示赞赏。
解决方案
更新:要使其首先工作,您将需要:
- 要添加“免费”运输类别(第一),
- 要启用 2 种运输方式:“免费送货”和“统一费率”,
- 在您的免费送货产品中,需要设置送货类别“免费”,
- 在您的其他产品中将没有任何定义的运输类别。
对于“免费送货”方式,您不会对其添加任何限制。
对于“统一费率”运输方式,您将按照以下屏幕截图进行设置:
魔术将由以下代码完成,其余部分将完成:
add_filter('woocommerce_package_rates', 'conditional_free_shipping', 10, 2); function conditional_free_shipping( $rates, $package ){ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return $rates;
## -- Your settings below -- ## $shipping_class = 'free'; // "Free" shipping class products $min_free_amount = 200; // Minimal Free shipping amount for normal products ## -- -- -- -- -- -- -- -- -- ## $has_free = false; // Initializing $products_total = 0; // Initializing // Loop through cart items foreach( $package['contents'] as $cart_item ) { if( $cart_item['data']->get_shipping_class() == $shipping_class ) { $has_free = true; } else { // Get the total purchased amount for normal product $products_total += $cart_item['line_total'] + $cart_item['line_tax']; } } foreach ( $rates as $rate_key => $rate ){ // 1. Only Free shipping products in cart OR both products kind in cart if( $has_free ) { if( 'flat_rate' === $rate->method_id ) unset( $rates[$rate_key] ); // Remove flat rate } // 2. Only normal products in cart else { // A. If it's under the min amount if( 'free_shipping' === $rate->method_id && $products_total < $min_free_amount ) unset( $rates[$rate_key] ); // Remove Free shipping // B. When min amount is reached elseif( 'flat_rate' === $rate->method_id && $products_total >= $min_free_amount ) unset( $rates[$rate_key] ); // Remove flat rate } } return $rates;
}
代码在您的活动子主题(活动主题)的 function.php 文件中。测试和工作。
您可能需要刷新运输缓存数据:在 Woocommerce 运输设置中禁用、保存和启用、保存当前运输区域的相关运输方式。
推荐阅读
- swift - 如何防止同一窗口的多个实例在 macOS 中打开?
- gitlab - 克隆同组项目,并在目标项目中使用源项目的 .gitlab-ci.yml 作为模板
- python - 如何从变量中提取时间并将其与python中的当前时间进行比较?
- laravel - Laravel 前端网站和 Laravel API 之间的通信,都在 Valet 下
- python - 多重继承 Python,super().__init__ 问题
- android - Flutter Bloc 不断重建小部件而不改变状态
- typescript - 通过括号访问键时如何将键限制为打字稿中定义的键
- javascript - 更改子元素的 src
- java - 如何在 Spring 中通过调用外部 API 来测试服务
- java - IntelliJ IDEA 中的“进程以退出代码 0 完成”是什么意思?