Check if a product variation is in cart in Woocommerce

Abhik picture Abhik · May 3, 2018 · Viewed 7.2k times · Source

I am trying display if a variation of a product is already in a cart or not (in single product page). A simple comparing of the product id with products in cart object is not working for variable product as the variation id is being loaded using ajax.

Here is my code that works in case the product type is other than variable.

<?php
/*
 * Check if Product Already In Cart
*/
function woo_in_cart( $product_id ) {
    global $woocommerce;

    if ( !isset($product_id) ) {
        return false;
    }

    foreach( $woocommerce->cart->get_cart() as $cart_item ) {
        if ( $cart_item['product_id'] === $product_id ){
            return true;
        } else {
            return false;
        }
    }
}  

Is there any way to make it work without jQuery?

Answer

James Kemp picture James Kemp · May 3, 2018

Do you mean $product_id could be the ID of a variation? If so, you can just get the parent ID if it exists:

/*
 * Check if Product Already In Cart
 */
function woo_in_cart( $product_id ) {
    global $woocommerce;

    if ( ! isset( $product_id ) ) {
        return false;
    }

    $parent_id  = wp_get_post_parent_id( $product_id );
    $product_id = $parent_id > 0 ? $parent_id : $product_id;

    foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
        if ( $cart_item['product_id'] === $product_id ) {
            return true;
        } else {
            return false;
        }
    }
}

If you mean your cart item is a variation, and $product_id is already the parent product ID, then your code should work already as is.

The $cart_item has 2 IDs: $cart_item['product_id'] and $cart_item['variation_id'].

So product_id will always be that of the parent product.