2016-10-03 15 views
5

私はWooCommerceで右フックを探しています。カートの量に達すると、従来の100ユニットなど、プロモーション商品をカートに追加する必要があります。特定のカート数量に達したときにプロモーション商品を追加する

私もフックを使用しました'init'私はそれが正しいとは思わないです。ここで

は私のコードです:私はその目的のために使用すべきフック

function add_free_product_to_cart(){ 
    global $woocommerce; 
    $product_id = 2006; 
    $found = false; 
    if (sizeof($woocommerce->cart->get_cart()) > 0) 
    { 
     foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) 
     { 
      $_product = $values['data']; 
      if ($_product->id == $product_id) 
      $found = true; 
     } 
     if(!$found) 
     { 
      $maximum = 100; 
      $current = WC()->cart->subtotal; 
      if($current > $maximum){ 
       $woocommerce->cart->add_to_cart($product_id); 
      }   
     }  
    } 
} 
add_action('woocommerce_add_to_cart', 'add_free_product_to_cart'); 

また、類似の問題に関連するリンクを教えてください。

おかげ

+0

申し訳ありませんが、このエラー は add_action( 'initの'、 'add_free_product_to_cart')でなければなりません。 –

答えて

8

あなたがカートにプロモーション製品を追加するために、特定のカートの量をターゲットにしているとして、あなたはカスタム構築された機能で、これを達成するためにwoocommerce_before_calculate_totalsフックを使用することができます。

あなたは、顧客が(あまりにもカスタム関数に埋め込むれる)カートを更新する場合、そのプロモーションの項目を削除することもあります。

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

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

    $promo_id = 99; // <=== <=== <=== Set HERE the ID of your promotional product 
    $targeted_cart_subtotal = 100; // <=== Set HERE the target cart subtotal 
    $has_promo = false; 
    $subtotal = 0; 

    if (!$cart_object->is_empty()){ 

     // Iterating through each item in cart 
     foreach ($cart_object->get_cart() as $item_key => $item_values){ 

      // If Promo product is in cart 
      if($item_values['data']->id == $promo_id) { 
       $has_promo = true; 
       $promo_key= $item_key; 
      } else { 
       // Adding subtotal item to global subtotal 
       $subtotal += $item_values['line_subtotal']; 
      } 
     } 
     // If Promo product is NOT in cart and target subtotal reached, we add it. 
     if(!$has_promo && $subtotal >= $targeted_cart_subtotal) { 
      $cart_object->add_to_cart($promo_id); 
      echo 'add'; 
     // If Promo product is in cart and target subtotal is not reached, we remove it. 
     } elseif($has_promo && $subtotal < $targeted_cart_subtotal) { 
      $cart_object->remove_cart_item($promo_key); 
     } 
    } 
} 

このコードは、あなたのアクティブな子テーマ(またはテーマ)のfunction.phpファイルまたは任意のプラグインファイルに行く:ここ

コードがあります。

このコードはテスト済みで、動作します。

関連スレッド:に更新WooCommerce - Auto add or auto remove a freebie product from cart

コード(2017年4月19日)

+0

私は1つの問題しか持っていません。テストに関しては、カート内の特定のアイテムの矢印を使用してカート内のアイテムの数を更新すると(あるカートの数に達するまで)、ページを更新するまでカートの金額に余分な手数料が加算されますチェックアウトを続ける...?これは奇妙な問題です。とにかく、フリー/プロモーションアイテムが追加または削除されたときにページを自動的に更新して、顧客が常に正しい金額を見ていることを確認できますか? – JStormThaKid

関連する問題