Home > Net >  How to exclude a specific product ID from being added to an array in WooCommerce
How to exclude a specific product ID from being added to an array in WooCommerce

Time:02-24

I'm trying to run a function if a statement is true (product id exist in an array), I will like to exclude a specific product id from this.

So far I have the below code which works fine but it still applies to all product, please how can I exclude this product?

if ( ! is_null( WC()->cart ) ) {
    // Initialize
    $product_ids = array();
    
    // Loop through cart contents
    foreach ( WC()->cart->get_cart_contents() as $cart_item ) {
        if ($cart_item['product_id'] != 32) {
        
            // Get product ID and push to array
            $product_ids[] = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
        }
    }
}

CodePudding user response:

There's nothing wrong with your code per se, but you're using $cart_item['product_id'] in your if condition, so if it is a variation ID your condition will not be met.

It's okay to use an if condition, however to apply this for 1 or more product IDs you better use NOT (!) in_array()

So you get:

if ( ! is_null( WC()->cart ) ) {
    // Initialize
    $product_ids = array();
    
    // Loop through cart contents
    foreach ( WC()->cart->get_cart_contents() as $cart_item ) {
        // Get product ID
        $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
        
        // Exlude Product ID(s), NOT in array 
        if ( ! in_array( $product_id, array( 32, 30, 817 ) ) ) {
            // Push to array
            $product_ids[] = $product_id;
        }
    }
}
  • Related