How to show if a product is already in cart in Woocommerce ?

In this tutorial we’ll learn how to display already in cart text if a product is already in cart.

This is our default single product screen.

woocommerceNow add this product to cart by clicking add to cart button. You’ll notice this doesn’t create any change on product page and the user donot know whether this product is already in cart or not. To achieve this add the following lines of code at the end of your functions.php file.

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );

 

function woo_custom_cart_button_text() {

 

                global $woocommerce;

 

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

                                $_product = $values['data'];

 

                                if( get_the_ID() == $_product->id ) {

                                                return __('Already in cart - Add Again?', 'woocommerce');

                                }

                }

 

                return __('Add to cart', 'woocommerce');

}

/**

* Change the add to cart text on product archives

*/
add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' );

function woo_archive_custom_cart_button_text() {

                global $woocommerce;

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

                                $_product = $values['data'];

                                if( get_the_ID() == $_product->id ) {

                                                return __('Already in cart', 'woocommerce');

                                }

                }

                return __('Add to cart', 'woocommerce');

}

You can access the function.php file here:

woocommerceNow if you refresh the single product page which is already in cart you will see the change in message there and it will state that product is already in cart.

woocommerce

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *