php - 如果 WooCommerce 购物车包含至少 X 个产品,则自动添加百分比折扣
问题描述
我正在尝试创建一个自动折扣,该折扣何时以及如果购物车包含至少三种或更多产品。
如果是这样,无论客户是否登录,都应给予 10% 的折扣。
这是我试图开始工作的代码(没有成功)。
add_action( 'woocommerce_cart_calculate_fees', 'wc_discount_when_more_than_three', 10, 1 );
function wc_discount_when_more_than_three( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 10; // 10% discount when cart has a minimum of three products
$discount = 0;
// check all cart items
foreach ( $cart->get_cart() as $cart_item ) {
// when quantity is more than 3
if( $cart_item['quantity'] > 3 ) {
// give 10% discount on the subtotal
$discount = $percentage / 100;
}
}
if( $discount > 0 )
$cart->add_fee( __( '10% OFF', 'woocommerce' ) , -$discount );
}
解决方案
这取决于您是要计算购物车中的产品数量还是产品数量(内容)的数量。
在我的回答中,我已经说明了两者,取消注释/删除/调整您的需求。
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Percentage
$percentage = 10;
/* Count contents in cart
*
* Product A: quantity in cart: 4
* Product B: quantity in cart: 1
* Product C: quantity in cart: 2
*
* count = 7
*
*/
//$count = $cart->cart_contents_count;
/* Count products in cart
*
* Product A
* Product B
* Product C
*
* count = 3
*/
$count = count( $cart->get_cart() );
// Greater than
if ( $count > 3 ) {
// Get subtotal
$subtotal = $cart->subtotal;
// Calculate
$discount = ( $subtotal / 100 ) * $percentage;
// Give % discount on the subtotal
$cart->add_fee( sprintf( __( '%s OFF', 'woocommerce'), $percentage . '%' ), -$discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
推荐阅读
- python - 如何从数据框中获取值?
- swift - Swift 协议导致无效的重新声明和混乱的函数表
- mysql - MySQL REGEXP_SUBSTR() 转义问题?
- sql - TransferText 将 csv 文件复制到临时表中
- postgresql - Postgresql:平均超过日期限制,分组依据
- javascript - 如何为引导下拉框设置焦点
- javascript - 是否可以在控制器中从 JSON 对象更改为 JSON 数组
- tensorflow - 使用带有注意力层的 Convlstm2d 预测结果时出现值错误?
- sql - 无法编写 SQL 查询
- amazon-web-services - 数据透视表中的计算字段小计未显示正确的值