将免费产品添加到woocommerce购物车

时间:2018-09-28 16:49:21

标签: woocommerce

我有一个代码段,根据所选的变体向woocommerce购物车添加了免费产品。代码工作正常,但是问题是当我重新加载页面时,数量增加了。我需要知道如何检查购物车的更新时间,或者要防止几次添加免费产品的情况。

这是代码段。

  if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    foreach(WC()->cart->get_cart() as $cart_item ) {
       global $product,$post;
       $added=false;
       $i=1;
       $item_name = $cart_item['data']->get_title();
       $quantity = $cart_item['quantity'];
       $price = $cart_item['data']->get_price();
       $variation_id = $cart_item['variation_id'];
       $variation = wc_get_product($variation_id);
       $terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
       foreach ($terms as $term) {
             $product_cat_id = $term->term_id;
             if($product_cat_id==65){
               if(strpos($variation->get_formatted_name(),"Dinner for 2",0) !== false ){      
                     WC()->cart->add_to_cart(104748);
                     $added=true;
               }else if(strpos($variation->get_formatted_name(),"Dinner for 4",0) !== false ){
                    WC()->cart->add_to_cart(104748,2);
                     $added=true;
               }else if(strpos($variation->get_formatted_name(),"Dinner for 6",0) !== false ){
                    WC()->cart->add_to_cart(104748,3);
                    $added=true;
               }else if(strpos($variation->get_formatted_name(),"Dinner for 8",0) !== false ){
                    WC()->cart->add_to_cart(104748,4);
                    $added=true;
               }else if(strpos($variation->get_formatted_name(),"Dinner for 10",0) !== false ){
                    WC()->cart->add_to_cart(104748,5);
                    $added=true;
               }else if(strpos($variation->get_formatted_name(),"Dinner for 12",0) !== false ){
                    WC()->cart->add_to_cart(104748,6);
                    $added=true;
               }
            }
       }
  }
}

感谢任何帮助 谢谢

1 个答案:

答案 0 :(得分:0)

您需要每次检查您的产品是否已经在购物车中。如果不是,则仅将产品添加到购物车,否则您需要跳过。

请使用此功能将您的产品添加到购物车-

function add_in_cart($product_id) { 
    global $woocommerce;
    var $isProductExist = false;

    foreach( $woocommerce->cart->get_cart() as $key => $val ) { 
        $_product = $val['data']; 
        if($product_id == $_product->id ) { 
        $isProductExist =true;
        break;
    } 
    if($isProductExist=false)
        $woocommerce->cart->add_to_cart($product_id);
}