php - 在 Woocommerce 中为两个或更多购物车商品启用免费送货
问题描述
在 Woocommerce 中,我想根据购物车商品的数量提供免费送货服务。首先,我开始查看可用的插件,但我找不到任何基于数量的简单解决方案。
我想要做的就是:买任何东西 2 并获得免费送货。
乱七八糟,我尝试了以下代码:
function free_ship( $is_available ) {
$count = 0;
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item) {
$count++;
}
echo $count;
if ( $count == 1 ) {
echo 'add one more for free shipping';
return $is_available;
} elseif ($count > 1) {
echo 'you get free shipping';
return false;
} else {
echo 'nothing in your cart';
return $is_available;
}
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_ship' );
但是在将商品添加到购物车时它会挂起。从购物车中取出东西时,它也是越野车。我想在 PHP 中解决这个问题,这样我就可以进一步添加更多独特的条件,因为它们将来会出现。
有什么建议吗?
解决方案
您的代码中存在一些错误,例如缺少参数、复杂性和过时的东西……请尝试以下操作:
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_for_x_cart_items', 10, 3 );
function free_shipping_for_x_cart_items( $is_available, $package, $shipping_method ) {
$item_count = WC()->cart->get_cart_contents_count();
if ( $item_count == 1 ) {
$notice = __("Add one more for free shipping");
$is_available = false;
} elseif ($item_count > 1) {
$notice = __("You get free shipping");
$is_available = true;
}
if ( isset($notice) ) {
wc_add_notice( $notice, 'notice' );
}
return $is_available;
}
此代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。
该WC_Cart
方法get_cart_contents_count()
获取所有项目(包括数量)的计数。
要获取 不同购物车商品的 数量(不包括数量),请替换以下行:
$item_count = WC()->cart->get_cart_contents_count();
有了这个:
$item_count = sizeof($package['contents']);
推荐阅读
- django - Heroku 部署成功,但未找到模块
- sql - 确定具有多个设备的表中设备的某些状态的持续时间
- java - 使用 RESTful Web 服务:控制器 Springboot 错误
- apache - .htaccess - 一个特定域的 SSL redicect 条件不起作用
- vue.js - 在 Vue 中,如何使用新的 devBaseUrl 选项?
- java - ClassName.class.getResource() 返回 null
- html - 展开 div 并覆盖其他 div
- jmeter - CSV 数据集在 JDBC 采样器请求之前执行
- mysql - 基于具有自连接的另一列值按值排序
- google-cloud-platform - 以编程方式编辑 Dataprep 配方