soliddigital
soliddigital

Reputation: 306

Conditional function that check if products are already in cart in Woocommerce 3

Hi solution provided here WooCommerce - Check if item's are already in cart working perfect. This is the function code:

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;
    };

}

Usage

  $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 :(';
}

But I need use as if(in_array) but no luck so far. What i doing wrong?

$my_products_ids_array = array("69286", "69287",);
if (in_array("69286", $my_products_ids_array)) {
    echo '<p>' . the_field ( 'cart_field', 'option' ) . '</p>';
}
if (in_array("69287", $my_products_ids_array)) {
    echo '<p>' . the_field ( 'cart_field-1', 'option' ) . '</p>';
}

Thank you

Upvotes: 1

Views: 2467

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Your main function code is outdated.

For Advanced custom fields (ACF):

  • you need to use get_field() (that return the field value) instead of the_field() (that echo the field value).
  • You may need to add a product ID as 2nd argument in get_field('the_slug', $product_id ).

So try:

function is_in_cart( $ids ) {
    // Initialise
    $found = false;

    // Loop Through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // For an array of product IDS
        if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
            $found = true;
            break;
        }
        // For a unique product ID (integer or string value)
        elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
            $found = true;
            break;
        }
    }

    return $found;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The custom conditional function is_in_cart( $ids ) accept a string (a unique product Id) or an array of product Ids.


Your revisited usage (ACF get_field may need a post ID (product ID)):

if ( is_in_cart( "69286" ) ) {
    echo '<p>' . get_field ( 'cart_field' ) . '</p>'; // or get_field ( 'cart_field', "69286" )
}
if ( is_in_cart( "69287" ) ) {
    echo '<p>' . get_field ( 'cart_field-1' ) . '</p>'; // or get_field ( 'cart_field', "69287" )
}

Upvotes: 3

Related Questions