我有两张优惠券,一张10美元,另一张5美元。如果价格低于50美元,客户输入折扣券10美元,用5美元代替这张优惠券,我想做下一步。
示例:
顾客在购物车里加了一件东西,总价是40美元,然后他用了10美元的优惠券。现在我需要用10美元替换当前的优惠券,然后继续结帐。
我能用的最简单的方法是什么?我尝试更改折扣价格,如下面的代码和此工作,但在其他地方WC给我显示旧优惠券,并计算从旧优惠券(按顺序页等)的所有数据,所以我真的需要替换一个优惠券到另一个(而不是计算他们的价格)当这个优惠券添加。它喜欢客户直接输入5美元的优惠券到折扣字段。
// Change price for discount
if( ! function_exists('custom_discount') ){
function custom_discount( $price, $values, $instance ) {
//$price represents the current product price without discount
//$values represents the product object
//$instance represent the cart object
//Get subtotal
$subtotal = WC()->cart->get_subtotal();
$coupon = WC()->cart->get_discount_total();
//if price < 50 and we have active coupon then we need decrease price to $5
if( $subtotal < 50 && ! empty( WC()->cart->get_applied_coupons() ) ){
$price = $subtotal - 5; //Wrong way ...
}
return $price;
}
add_filter( 'woocommerce_get_discounted_price', 'custom_discount', 10, 3);
}
发布于 2020-03-19 17:14:43
这需要使用与cart和Ajax启用的相关的动作钩子(如woocommerce_calculate_totals
),因为它将处理客户在cart页面中所做的所有更改:
add_action( 'woocommerce_calculate_totals', 'discount_based_on_cart_subtotal', 10, 1 );
function discount_based_on_cart_subtotal( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetitions
if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )
return;
// Your coupons settings below
$coupon_05_off = '$5-Off';
$coupon_10_off = '$10-Off';
// When cart subtotal is below 50
if ( $cart->subtotal < 50 ) {
if ( $cart->has_discount( $coupon_10_off ) ) {
$cart->remove_coupon( $coupon_10_off ); // Remove $10.00 fixed discount coupon
if ( ! $cart->has_discount( $coupon_05_off ) ) {
$cart->apply_coupon( $coupon_05_off ); // Add $5.00 fixed discount coupon
}
}
}
// When cart subtotal is up to 50
else {
if ( $cart->has_discount( $coupon_05_off ) ) {
$cart->remove_coupon( $coupon_05_off ); // Remove $5.00 fixed discount coupon
if ( ! $cart->has_discount( $coupon_10_off ) ) {
$cart->apply_coupon( $coupon_10_off ); // Add $10.00 fixed discount coupon
}
}
}
}
代码在您的活动子主题(或活动主题)的functions.php文件中。测试和工作。
发布于 2020-03-18 17:41:50
我已经测试过这一点,并能确认它的工作,即使在你改变后,在购物车中的产品要么低于或超过50美元。
subtotal;
// If cart subtotal is less than 50 add or remove coupons
if ($cart_subtotal < 50) {
if ( $woocommerce->cart->has_discount( $coupon10off ) ) {
WC()->cart->remove_coupon( $coupon10off );
$woocommerce->cart->add_discount( $coupon5off );
}
}
// If cart subtotal is greater 49 add or remove coupons
if ($cart_subtotal > 49 ) {
if ( $woocommerce->cart->has_discount( $coupon5off ) ) {
WC()->cart->remove_coupon( $coupon5off );
$woocommerce->cart->add_discount( $coupon10off );
}
}
}
https://wordpress.stackexchange.com/questions/360709
复制相似问题