woocommerce how to get $cart_item_key for a single product

26,316

Solution 1

You have to set the remove link for each product within loop like this,

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {

 echo $cart_item_key;
 if($cart_item['product_id'] == $your_product_id_to_remove ){
    //remove single product
 }
} 

In any situation you have cart item listing; from that you have to remove, so foreach will work with your requirement.

Hope its helps..

Solution 2

This code worked for me. Thanks to Jobin Jose (https://stackoverflow.com/users/1258004/jobin-jose) for the solution!

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
    if ($cart_item['product_id'] == $product->id ) {
        echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf('<a href="%s" class="remove" title="%s">&times;</a>', esc_url( $woocommerce->cart->get_remove_url( $cart_item_key) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key );
}
Share:
26,316
Sarah McLachlane
Author by

Sarah McLachlane

Updated on August 03, 2022

Comments

  • Sarah McLachlane
    Sarah McLachlane almost 2 years

    I'm implementing a Remove Item button next to the add to cart button however I have a problem getting the variable $cart_item_key for a single product. I have the global variables $woocommerce and $product but the only way $cart_item_key is used is a foreach which doesn't help me at all as I need my code to be added in add-to-cart.php.

  • Alex Mulchinock
    Alex Mulchinock over 7 years
    This seems like a very inefficient way to achieve this. I'm aware that the structure of WooCommerce more or less forces this type of solution - however, we're essentially saying: "For each item in the cart, check it against all of the other items in the cart, if it's a match - do something". Doing basic maths we can see clearly that we have to iterate through our cart items Y squared times (where Y is the number of items in our cart). 1 item - 2 iterations 2 items - 4 iterations 3 items - 9 iterations 4 items - 16 iterations