我正在寻求有关如何修改现有代码以实现以下目标的帮助:
仅对每个登录用户的特定产品(ID:848)的前 3 个实例应用 15% 的折扣。
add_action('woocommerce_cart_calculate_fees', 'custom_discount_for_logged_in_users', 10, 1);
function custom_discount_for_logged_in_users($cart) {
$target_product_id = 848;
if (is_user_logged_in() && in_array($target_product_id, array_column($cart->get_cart(), 'product_id'))) {
$discount = $cart->subtotal * 0.15;
$cart->add_fee('15% Discount', -$discount, true);
}
}
这应该适用于您的代码。它未经测试,但我添加了一个
user_meta
来存储用户获得折扣的次数。然后它会检查以确保可以进行折扣。
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_logged_in_users', 10, 1 );
function custom_discount_for_logged_in_users( $cart ) {
$target_product_id = 848;
if ( is_user_logged_in() && in_array( $target_product_id, array_column( $cart->get_cart(), 'product_id' ), true ) ) {
$user_id = get_current_user_id();
$first_three = get_user_meta( $user_id, 'first_three_discount', true );
$number_applied = ( ! empty( $first_three ) ) ? absint( $first_three ) : 0;
if ( 3 > $number_applied ) {
$discount = $cart->subtotal * 0.15;
$cart->add_fee( '15% Discount', -$discount, true );
$number_applied++;
update_user_meta( $user_id, 'first_three_discount', $number_applied );
}
}
}