Here’s the story: I’m working with one of my freelance clients and I need to show certain content in the Checkout (a product-specific “Terms and Conditions”) if such product is in the Cart.
Now, I’ve always looked for products in the Cart by “looping” through the Cart with a foreach (here, for example: Apply a Coupon Programmatically if a Product is in the Cart). But as I said, after some random research, I found out about another magic WooCommerce function: “find_product_in_cart()“. Which means finding a product in the Cart doesn’t require custom loops or complex PHP… it’s just a “one liner”. Enjoy!
WooCommerce: find if product ID is in the Cart
PHP Snippet: Easily Check if Product ID is Contained in the Cart – WooCommerce
Note: I believe this method only works with “simple” products. In case, use the snippet alternative you find below.
/**
* @snippet Check if Product ID is in the Cart - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @testedwith WooCommerce 3.9
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_before_cart', 'tutoraspire_find_product_in_cart' );
function tutoraspire_find_product_in_cart() {
$product_id = 282;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
$notice = 'Product ID ' . $product_id . ' is in the Cart!';
wc_print_notice( $notice, 'notice' );
}
}
PHP Snippet Alternative (the “old” way, still works): Check if Product ID is in the Cart Via a Foreach Loop – WooCommerce
/**
* @snippet Check if Product ID is in the Cart (Alternative) - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @testedwith WooCommerce 3.9
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_before_cart', 'tutoraspire_find_product_in_cart_alt' );
function tutoraspire_find_product_in_cart_alt() {
$product_id = 282;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
if ( $product_in_cart === $product_id ) $in_cart = true;
}
if ( $in_cart ) {
$notice = 'Product ID ' . $product_id . ' is in the Cart!';
wc_print_notice( $notice, 'notice' );
}
}