Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

Show if a product is already in cart in Woocommerce

We Will show how to display product is already in cart text if a product is already in cart. Here is code for WooCommerce that changes the ‘add to cart’ button text when a product is already in cart. It uses two filters, one to change the text on the product page, and one for the products list.

So, here is code. which you can add in your theme’s functions.php file of your active child theme (or theme).Save file.Now 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.

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woocommerce_cart_button_text' );
function woocommerce_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', 'woocommerce_archive_cart_button_text' );

function woocommerce_archive_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');
}
Exit mobile version