2017-07-24 215 views
2

如果購物車中包含特定類別的產品,我試圖自動添加優惠券代碼。顯示折扣金額後,必須在合計中更新價格。根據產品類別自動添加WooCommerce優惠券代碼

但我無法看到總數的任何變化,請幫助我。

我的代碼:

add_action('wc_cart_product_subtotal' , 'getsubtotalc'); 
function getsubtotalc ($product_subtotal, $_product, $quantity, $object) { 
    if(is_cart() || is_checkout()) { 
     global $woocommerce, $product; 
     global $total_qty; 
     /*$coupon_code = 'drawer'; 
     if ($woocommerce->cart->has_discount($coupon_code)) return;*/ 

     foreach ($woocommerce->cart->cart_contents as $product) { 
      if(has_term(array('t-shirts-d','socks-d','joggers-d','boxers-d'), 'product_cat', $cart_item['product_id'])){ 
       $coupon_code = 'drawer'; 
       if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) { 
        $woocommerce->show_messages(); 
       } 
       echo '<div class="woocommerce_message"><strong>The number of Product in your order is greater than 10 so a 10% Discount has been Applied!</strong> 
</div>'; 
      } 
     } 
    } 
} 

感謝

回答

2

這裏是正確的鉤和代碼,這將自動應用優惠券代碼,當車項目是從具體的產品類別和將更新購物車總計:

add_action('woocommerce_before_calculate_totals', 'wc_auto_add_coupons_categories_based', 10, 1); 
function wc_auto_add_coupons_categories_based($cart_object) { 

    // HERE define your product categories and your coupon code 
    $categories = array('t-shirts-d','socks-d','joggers-d','boxers-d'); 
    $coupon = 'drawer'; 

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

    // Initialising variables 
    $has_category = false; 

    // Iterating through each cart item 
    foreach ($cart_object->get_cart() as $cart_item) { 
     // If a cart item belongs to a product category 
     if(has_term($categories, 'product_cat', $cart_item['product_id'])){ 
      $has_category = true; // Set to true 
      break; // stop the loop 
     } 
    } 

    // If conditions are matched add the coupon discount 
    if($has_category && ! $cart_object->has_discount($coupon)){ 
     // Apply the coupon code 
     $cart_object->add_discount($coupon); 

     // Optionally display a message 
     wc_add_notice(__('my message goes here'), 'notice'); 
    } 
    // If conditions are not matched and coupon has been appied 
    elseif(! $has_category && $cart_object->has_discount($coupon)){ 
     // Remove the coupon code 
     $cart_object->remove_coupon($coupon); 

     // Optionally display a message 
     wc_add_notice(__('my warning message goes here'), 'alert'); 
    } 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

代碼在woocommerce 3+上測試並正常工作。

如果已應用優惠券,並且特定產品類別的購物車項目全部被刪除,優惠券也將被刪除。

+0

這工作完美,並感謝使代碼看起來乾淨。 – SandeepTete

相關問題