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.

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