woocommerce how to get $cart_item_key for a single product

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.

Related posts

Leave a Reply

2 comments

  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..

  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 );
    }