我使用此代码为注册用户设置“欢迎”折扣:
add_action( 'woocommerce_cart_calculate_fees', 'personal_discount_based', 20, 1 );
function personal_discount_based( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$user = get_user_data();
$usId = $user->ID;
update_user_meta( $usId, 'discount', 5 );
$personalDisconte = $user->discount;
$orderNumbers = wc_get_customer_order_count($usid);
if ( ! $personalDisconte == true )
return;
$percentage = $personalDisconte;
$discount = $cart->get_subtotal() * $percentage / 100;
if(!empty($orderNumbers) && $orderNumbers == 1){
update_user_meta( $usId, 'discount', 0 );
}elseif( $orderNumbers > 1){
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}else{
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
}
这段代码完成了它的功能。但现在我面临另一个问题。当然,折扣适用于整个订单金额。在这种情况下,订单可能已经包含有折扣的产品。而且这个选项不适合卖家。
一般情况下,此代码生成的折扣可能不会应用于订单总额。但仅限于那些没有折扣的产品。
例如,用户向购物车添加了三个产品:
第一项 50$ 第二项 75$ 第三项 90$(原价 120$)
所以,我必须对 50 + 75 的总和应用折扣(这些是正价产品) 50 + 75 - 5% 加 90 后的结果就是最终的总和。
目前,我不知道如何做到这一点,也不确定是否可以做到这一点。如果有人可以提供帮助,请提供建议。
最佳答案
如果您要为尚未购买的新客户应用欢迎折扣,您的代码就毫无意义,因此我简化并简化了您的代码。
然后,要获取非“特价”商品的购物车小计,您需要遍历购物车商品才能获取它。
重新访问的代码:
add_action( 'woocommerce_cart_calculate_fees', 'welcome_discount_on_normal_items', 20, 1 );
function welcome_discount_on_normal_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$user_id = get_current_user_id();
if( $user_id > 0 ) {
$percentage = 5; // Discount percentage
$orders_count = (int) wc_get_customer_order_count($user_id);
$subtotal = 0; // Initializing
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
// Add non on sale items to subtotal
if( ! $cart_item['data']->is_on_sale() ) {
$subtotal += $cart_item['line_subtotal'];
}
}
// Discount percentage amount on non "on sale" items subtotal
$discount = $subtotal * $percentage / 100;
// For new customer only that haven't purchase yet
if( $subtotal > 0 && $orders_count === 0 ) {
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
}
}
代码位于事件子主题(或事件主题)的functions.php 文件中。经过测试并有效。
关于php - 对 WooCommerce 中的非 "on sale"商品应用欢迎折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65097517/