Function to Check if given Array of Product IDs are present in the Cart

In this blog post, we will discuss a useful function that allows you to check whether a given array of product IDs is present in the WooCommerce cart. This function can come in handy when you need to perform specific actions based on the presence of certain products in the customer’s cart. I will provide a code snippet that you can easily integrate into your WordPress project.

/**
 * Are given products in cart.
 *
 * @param int $product_ids Product Ids.
 *
 * @return bool
 */
function are_products_in_cart( $product_ids ) {
	if ( empty( WC()->cart ) ) {
		return false;
	}

	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		$product_id = $cart_item['product_id'];

		if ( $cart_item['data']->is_type( 'variation' ) ) {
			$product_id = $cart_item['data']->get_parent_id();
		}

		if ( in_array( $product_id, $product_ids ) ) {
			return true;
		}
	}

	return false;
}

Note: This function returns true if at least one product is present in the cart.

How to Check if any of the given Product Categories are present in the cart

Similarly, if you want to check whether any products belonging to the given product categories are present in the cart, you can use this function:

/**
 * Are categories present in the cart.
 *
 * @param array $categories The product category name/term_id/slug, or an array of them to check for.
 *
 * @return bool
 */
function are_categories_present_in_cart( $categories ) {
    if ( empty( WC()->cart ) ) {
        return false;
    }

    $has_item = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product    = $cart_item['data'];
        $parent_id  = $product->get_parent_id();
        $product_id = empty( $parent_id ) ? $product->get_id() : $parent_id;

        if ( has_term( $categories, 'product_cat', $product_id ) ) {
            $has_item = true;

            // Break because we only need one "true" to matter here.
            break;
        }
    }

    return $has_item;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

WooCommerce Tips: Conditionally Hiding Order Notes for Virtual Products

WooCommerce Tips: Conditionally Hiding Order Notes for Virtual Products