【问题标题】:Apply a coupon programmatically in Woocommerce在 Woocommerce 中以编程方式应用优惠券
【发布时间】:2013-03-22 14:25:22
【问题描述】:

在 Woocommerce 中,我试图找到一种方法,如果购物车中的重量超过 100 磅,则为整个客户的订单提供 10% 的折扣。我正在实现这一目标。对于下一步,我正在寻找一种通过functions.php通过action/hook以编程方式应用优惠券代码的方法。

看来我可以使用函数 woocommerce_ajax_apply_coupon 来执行此操作(http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html),但我不确定如何使用它。

到目前为止,我已经修改了 cart.php 以获取购物车中所有产品的总重量,我已经创建了一个应用折扣的优惠券(如果手动输入),并且我已经向函数添加了一些代码。 php 来检查重量并向用户显示一条消息。

编辑:部分代码已删除,完整的代码包含在下面的解决方案中。


感谢弗雷尼的指导。这是在满足条件时成功应用折扣券并在不再满足时将其删除的工作最终结果:

/* Mod: 10% Discount for weight greater than 100 lbs 
Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $total_weight of cart:
        global $total_weight;
        $total_weight = $woocommerce->cart->cart_contents_weight;
*/
add_action('woocommerce_before_cart_table', 'discount_when_weight_greater_than_100');
function discount_when_weight_greater_than_100( ) {
    global $woocommerce;
    global $total_weight;
    if( $total_weight > 100 ) {
        $coupon_code = '999';
        if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        echo '<div class="woocommerce_message"><strong>Your order is over 100 lbs so a 10% Discount has been Applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
    }
}

/* Mod: Remove 10% Discount for weight less than or equal to 100 lbs */
add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less');
function remove_coupon_if_weight_100_or_less( ) {
    global $woocommerce;
    global $total_weight;
    if( $total_weight <= 100 ) {
        $coupon_code = '999';
        $woocommerce->cart->get_applied_coupons();
        if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        $woocommerce->cart->calculate_totals();
    }
}

【问题讨论】:

    标签: php wordpress woocommerce discount coupon


    【解决方案1】:

    首先,创建一张折扣券(通过http://docs.woothemes.com/document/create-a-coupon-programatically/):

    $coupon_code = 'UNIQUECODE'; // Code - perhaps generate this from the user ID + the order ID
    $amount = '10'; // Amount
    $discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
    
    $coupon = array(
        'post_title' => $coupon_code,
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type'     => 'shop_coupon'
    );    
    
    $new_coupon_id = wp_insert_post( $coupon );
    
    // Add meta
    update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
    update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
    update_post_meta( $new_coupon_id, 'individual_use', 'no' );
    update_post_meta( $new_coupon_id, 'product_ids', '' );
    update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
    update_post_meta( $new_coupon_id, 'usage_limit', '1' );
    update_post_meta( $new_coupon_id, 'expiry_date', '' );
    update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
    update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
    

    然后将该优惠券应用于您的订单:

    if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code )))
        $woocommerce->show_messages();
    

    最后一个函数返回一个 BOOL 值:如果折扣成功,则返回 TRUE,如果由于各种原因中的任何一个而失败,则返回 FALSE。

    【讨论】:

    • 由于我在后台已经有一张优惠券:“999”我只添加了您提供的代码来应用优惠券。但是,当我转到 woocommerce 购物车页面时,我现在收到错误消息:在第 65 行 [the if statement with add_discount] [path to...] functions.php 中的非对象上调用成员函数 add_discount()。我已经更新了原始帖子中的代码,以向您展示它的外观。
    • 尝试添加 global $woocommerce; 以及您的 $total_weight 行。
    • 谢谢,成功了!所以现在我能够成功应用折扣,但现在我注意到另一个问题......如果用户删除了一些购物车物品并且购物车回到 100 磅或更少,那么折扣仍然存在。如果购物车不再符合条件,我正在寻找一种取消折扣的方法,这样用户将无法利用此优惠券。我希望有一个 remove_discount 函数,它的工作方式与 add_discount 相反,但我无法在 Woocommerce API 文档中找到一个:docs.woothemes.com/wc-apidocs
    • 我注意到有一种方法可以通过单击购物车页面上的链接手动删除折扣:“订单折扣 [删除]”。如果重量回到 100 磅或更少,我正在寻找使用 javascript 自动触发此链接的方法(尽管并不理想)。我能够从functions.php执行原始javascript,但由于某种原因无法使用jquery(即使jquery 1.8.3显然已加载到购物车页面上)。我试图定位链接并使用点击功能(上面更新),我还没有到那里,即使它确实有效,也只能在 IE8+ 中使用:(
    • 如果您在技术上回答了我的原始问题,那么仅针对“remove_discount”功能和 javascript 问题发布一个新问题是否更有意义。
    【解决方案2】:

    我使用了这个解决方案,但它包含一个错误,因为 OP 编写了它。如果用户跳过预览购物车并直接进入结帐表单,则不会应用优惠券。这是我的解决方案。

    // Independence day 2013 coupon auto add
    // Add coupon when user views cart before checkout (shipping calculation page).
    add_action('woocommerce_before_cart_table', 'add_independence_day_2013_coupon_automatically');
    
    // Add coupon when user views checkout page (would not be added otherwise, unless user views cart first).
    add_action('woocommerce_before_checkout_form', 'add_independence_day_2013_coupon_automatically');
    
    // Check if php function exists.  If it doesn't, create it.
    if (!function_exists('add_independence_day_2013_coupon_automatically')) {
    
        function add_independence_day_2013_coupon_automatically() {
    
            global $woocommerce;
            $coupon_code = 'independencedaysale';
            $bc_coupon_start_date = '2013-06-30 17:00:00';
            $bc_coupon_end_date = '2013-07-08 06:59:59';
    
            // Only apply coupon between 12:00am on 7/1/2013 and 11:59pm on 7/7/2013 PST.
            if ((time() >= strtotime($bc_coupon_start_date)) &&
                (time() <= strtotime($bc_coupon_end_date))) {
    
                // If coupon has been already been added remove it.
                if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {
    
                    if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {
    
                        $woocommerce->show_messages();
    
                    }
    
                }
    
                // Add coupon
                if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
    
                    $woocommerce->show_messages();
    
                } else {
    
                    $woocommerce->clear_messages();
                    $woocommerce->add_message('Independence day sale coupon (10%) automatically applied');
                    $woocommerce->show_messages();
    
                }
    
                // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
                $woocommerce->cart->calculate_totals();
    
            } else {
    
                // Coupon is no longer valid, based on date.  Remove it.
                if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {
    
                    if ($woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {
    
                        $woocommerce->show_messages();
    
                    }
    
                    // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
                    $woocommerce->cart->calculate_totals();
    
                }
    
            }
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      2017 / 2019 自 Woocommerce 3

      一个挂钩函数中的以下紧凑代码将根据显示自定义消息的购物车总重量添加折扣(优惠券)。如果客户更改购物车商品,代码将检查购物车商品,如果购物车重量低于定义的重量,则删除折扣(优惠券)。

      代码:

      add_action('woocommerce_before_calculate_totals', 'discount_based_on_weight_threshold');
      function discount_based_on_weight_threshold( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
              return;
      
          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
              return;
      
          // Your settings
          $coupon_code      = 'onweight10'; // Coupon code
          $weight_threshold = 100; // Total weight threshold
      
          // Initializing variables
          $total_weight     = $cart->get_cart_contents_weight();
          $applied_coupons  = $cart->get_applied_coupons();
          $coupon_code      = sanitize_text_field( $coupon_code );
      
          // Applying coupon
          if( ! in_array($coupon_code, $applied_coupons) && $total_weight >= $weight_threshold ){
              $cart->add_discount( $coupon_code );
              wc_clear_notices();
              wc_add_notice( sprintf(
                  __("Your order is over %s so a %s Discount has been Applied! Your total order weight is %s.", "woocommerce"),
                  wc_format_weight( $weight_threshold ), '10%', '<strong>' . wc_format_weight( $total_weight ) . '</strong>'
              ), "notice");
          }
          // Removing coupon
          elseif( in_array($coupon_code, $applied_coupons) && $total_weight < $weight_threshold ){
              $cart->remove_coupon( $coupon_code );
          }
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 2019-04-05
        • 2020-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多