WooCommerce 使用 add_to_cart 添加产品

WooCommerce add product with add_to_cart

通常这听起来像是一项非常简单的任务。当将特定产品添加到购物车时,我想将(礼品)产品添加到购物车。一旦“普通产品”被删除,免费产品也应该被删除。

我目前的方法是使用自定义元数据将免费产品添加到购物车。如果单击删除按钮,它将检查元数据并仅删除这些元数据。

我的问题是免费产品只添加到购物车一次。如果我删除此“检查”,该功能将不再起作用。我做错了什么?

/* Add Free Gift for Products */
function gift_add_product_to_cart() {
  $product_id = array(20070, 39039); // Product Id of the free product which will get added to cart
  $allowedprdIds = array(38162, 38157); // Product Ids of the products where the free product will be added
  $is_present = false;
  $is_allowedPrd = false;
  $cart = WC()->cart->get_cart();
  //check if product already in cart
  if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
      $_product = $values['data'];
      if (in_array($_product->get_id(), $product_id)){
       $is_present = true;
      }
      if (in_array($_product->get_id(), $allowedprdIds) ){
       $is_allowedPrd = true;
      }        
    }

    // if free product not found, add it
    if (!$is_present && $is_allowedPrd){
      foreach($product_id as $freeProduct => $id){
        /*WC()->cart->add_to_cart(20070);*/
        WC()->cart->add_to_cart($id,1, NULL, NULL, array('freeDosMas' => 'yes'));
      }
    }

  }
}
add_action( 'woocommerce_add_to_cart', 'gift_add_product_to_cart', 10, 2 );
 
/* Remove Free Product if Produkt removed */
function remove_gift_from_cart() {
  global $woocommerce;
  $prod_to_remove = array(20070, 39039); // Product ID of Free Product
  $allowedprdIds = array(38162, 38157);
  $is_freeGift = false;

  foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      if (in_array($cart_item['product_id'], $prod_to_remove) && $cart_item['freeDosMas'] == 'yes'){
       $is_freeGift = true;
      }
      if (in_array($cart_item['product_id'], $allowedprdIds) ){
       $is_allowedPrd = true;
      } 
  }

  if($is_freeGift && !$is_allowedPrd){
    foreach($prod_to_remove as $removeProduct => $id){
      if (in_array($cart_item['product_id'], $prod_to_remove)) {
        WC()->cart->remove_cart_item( $cart_item_key );
      }  
    }
  }

}
add_action( 'woocommerce_cart_item_removed', 'remove_gift_from_cart', 10, 2  );

好的,知道了!

By inserting a new product using WC()->cart->add_to_cart in the action woocommerce_add_to_cart function it creates a indefinite recursive loop which throws the error.

We can fix this by removing the add_to_cart action before inserting the new product:

remove_action('woocommerce_add_to_cart', __FUNCTION__);

()