I use a code that changes the text and style of the "Add to Cart" button for a product if the item is already in the cart. Many thanks to 7uc1f3r for this.
/* for single product */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'single_product_button_text' );
function single_product_button_text( $text ) {
if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
$text = 'Product in cart';
}
return $text;
}
/* for archive/category pages */
add_filter( 'woocommerce_product_add_to_cart_text', 'products_button_text', 20, 2 );
function products_button_text( $text, $product ) {
if(
$product->is_type( 'simple' )
&& $product->is_purchasable()
&& $product->is_in_stock()
&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
) {
$text = 'Product in cart';
}
return $text;
}
function action_wp_footer() {
?>
<script>
jQuery(document).ready(function($) {
var selector = '.add_to_cart_text:contains("Product in cart")';
// Selector contains specific text
if ( $( selector ).length > 0 ) {
$( selector ).addClass( 'product-is-added' );
} else {
$( selector ).removeClass( 'product-is-added' );
}
});
</script>
<?php
}
add_action( 'wp_footer', 'action_wp_footer' );
After adding a product to the cart, I have to refresh the page each time to get new text and button style.
UPDATE
I also used Relabel "add to cart" button after add to cart in WooCommerce 2nd function code to change the text and style of the button using AJAX. The text changes, but all styles break.
Unfortunately, adding styles on the echo '<div class="add_to_cart_text">' . $new_text . '</div>';
line doesn't work.
Any help?