WooCommerce: Check if items are already in cart

后端 未结 4 1858
无人共我
无人共我 2020-12-09 00:07

I found this great snippet from this website

The following is the function to check if a specific product exists in cart:

        function woo_in_ca         


        
4条回答
  •  独厮守ぢ
    2020-12-09 00:17

    There was a mistake in the woo_in_cart function. Here the correct one:

     function woo_in_cart($arr_product_id) {
        global $woocommerce;
        $cartarray=array();
    
        foreach($woocommerce->cart->get_cart() as $key => $val ) {
           $_product = $val['product_id'];
           array_push($cartarray,$_product);
        }
    
        if (!empty($cartarray)) {
           $result = array_intersect($cartarray,$arr_product_id);
        }
    
        if (!empty($result)) {
           return true;
        } else {
           return false;
        };
    
    }
    

    Here an example of usage:

    //Set IDs Array variable
    
    $my_products_ids_array = array(22,23,465);
    if (woo_in_cart($my_products_ids_array)) {
      echo 'ohh yeah there some of that products in!';
    }else {
      echo 'no matching products :(';
    }
    

提交回复
热议问题