【问题标题】:Auto apply / remove a coupon code based on cart items in Woocommerce根据 Woocommerce 中的购物车项目自动应用/删除优惠券代码
【发布时间】:2019-08-17 04:57:15
【问题描述】:

如果购物车至少有 2 件商品,我想将优惠券代码应用于购物车。如果没有,则优惠券将不适用并显示更改消息,如果已申请,则将显示成功消息这是我的代码我尝试过的代码不能像我想要的那样工作

add_action( 'woocommerce_before_calculate_totals','conditionally_auto_add_coupon', 30, 1 );

function conditionally_auto_add_coupon( $cart ) {

    if ( is_admin() && !defined('DOING_AJAX') ) return; // Exit

    // HERE set the coupon code (in lowercase)
    $coupon_code = 'mycode';

    $total_item = 0;

    if (WC()->cart->has_discount('mycode')) {

        foreach( $cart->get_cart() as $cart_item ){
          $total_item++;
        }
        if($total_item < 2){
            $cart->remove_coupon( $coupon_code );

            wc_add_notice( __('you have only 1 item in cart'), 'alert');
        }
        else{
            $cart->add_discount( $coupon_code );

            wc_add_notice( __('coupon added'), 'notice');
        }
    }
}

欢迎任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce cart coupon


    【解决方案1】:

    请使用"Smart Coupon For Woocommerce"插件实现自动优惠券功能,

    请参考这个code svn repo。

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_conditionally', 10, 1 );
      function auto_apply_coupon_conditionally( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
              return;
      
          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
              return;
      
          $coupon_code = 'summer'; // HERE set the coupon code (in lowercase)
          $applied     = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false;
          $item_count  = sizeof( $cart->get_cart() );
          $total_item  = 0;
      
          // Remove coupon
          if ( $item_count < 2 && $applied ) {
              $cart->remove_coupon( $coupon_code );
              wc_clear_notices();
              wc_add_notice( __('You have only 1 item in cart'), 'error');
          }
          // Add coupon
          elseif ( $item_count >= 2 && ! $applied ) {
              $cart->apply_coupon( $coupon_code );
              wc_clear_notices();
              wc_add_notice( __('A coupon has been added'), 'notice' );
          }
      }
      

      代码进入您的活动子主题(或活动主题)的 function.php 文件中。测试和工作

      【讨论】:

      • 感谢代码,但问题是当我将优惠券放在优惠券字段时,购物车只有 1 件商品,优惠券已应用并向我显示默认成功消息可以告诉我出了什么问题?
      • @mdkamrul 此代码并非用于手动添加优惠券......它自己制作......它自动应用或自动删除优惠券代码。 (我已将钩子改回woocommerce_before_calculate_totals)……对我来说,代码在我的测试服务器上完美运行。
      • 抱歉造成误会。但我需要手动而不是自动。你能给出一个解决方案吗?
      • 实际上这是手动应用优惠券而不是自动。我也改变了你说的动作 woocommerce_before_calculate_totals 但没有改变,这和以前一样。你能改一下代码吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2020-11-15
      • 2017-09-15
      • 2019-07-24
      • 2018-09-19
      • 2021-05-30
      相关资源
      最近更新 更多