【问题标题】:Auto apply a coupon for a specific product based on Woocommerce cart subtotal根据 Woocommerce 购物车小计自动为特定产品应用优惠券
【发布时间】:2019-07-24 00:31:59
【问题描述】:

参考这个问题:Apply a coupon programmatically in Woocommerce 然后这个问题:How to apply an automatic discount in WooCommerce based on cart total?

这里是完整的菜鸟。当购物车中其他产品的小计为 40 美元时,我需要将现有的优惠券自动应用于一个特定产品。而且我需要确保应用折扣不会因为将总金额降至 40 美元以下而将优惠券取出而造成循环。

我不确定如何修改此代码来做到这一点:

add_action('woocommerce_before_checkout_process','add_discount_at_checkout');

function add_discount_at_checkout(){
global $woocommerce;
$minorder = 99;
if( $woocommerce->cart->get_cart()->cart_contents_total>$minorder){

 //APPLY COUPON HERE

}
}


【问题讨论】:

  • 我建议您添加一些您尝试过的代码变体。并解释随后的结果。仅仅添加一些您认为可以使用的代码并不能容纳太多的水。另外,这个问题可能最好放在wordpress.stackexchange.com
  • 我还没有尝试过任何代码,因为我不是程序员,购物车是不稳定的(长篇故事),所以随意尝试是危险的,我还没有找到代码具体是我要问的。

标签: php wordpress woocommerce coupon discount


【解决方案1】:

首先需要将目标优惠券代码设置为仅限目标产品:

如果购物车小计(不包括此特定购物车商品)达到$40,则以下代码将仅对特定购物车商品应用特定优惠券(折扣):

add_action('woocommerce_before_calculate_totals', 'discount_based_on_total_threshold');
function discount_based_on_total_threshold( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Your settings
    $coupon_code      = 'summer'; // Coupon code
    $amount_threshold = 40; // Total amount threshold
    $targeted_product = 37; // Targeted product ID

    // Initializing variables
    $total_amount     = 0;
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );
    $found            = false;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ) {
        if( ! in_array( $targeted_product, array( $cart_item['product_id'], $cart_item['data']->get_id() ) ) ) {
            // Get the cart total amount (excluding the targeted product)
            $total_amount += $cart_item['line_total'] + $cart_item['line_tax'];
        } else {
            // Targeted product is found
            $found = true;
        }
    }

    // Applying coupon
    if( ! in_array($coupon_code, $applied_coupons) && $found && $total_amount >= $amount_threshold ){
        $cart->add_discount( $coupon_code );
    }
    // Removing coupon
    elseif( in_array($coupon_code, $applied_coupons) && ( $total_amount < $amount_threshold || ! $found ) ){
        $cart->remove_coupon( $coupon_code );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

【讨论】:

  • 我遇到了冲突,因为我已经将优惠券设置为最低消费 40.00 美元。它不允许自动应用优惠券。一旦我从优惠券本身中删除了它,它就完美地工作了。
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 2019-08-17
  • 2013-11-28
相关资源
最近更新 更多