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?
2
Answers
I have something similar implemented on a website.
What might help is
.on('input change', function() { // Your code here }).change();
this updated my product page in real time and I believe you should be able to find a way to implement it to change the text on the add to cart button.
I am new to JavaScript so please bear with me and I hope my answer was at least a little helpful.
As your website shop and archives pages are very custom (doesn’t have the default WooCommerce html structure) you need a very custom jQuery code made for your website.
Your Ajax add to cart button has by default this output html example:
And you need on Ajax added to cart to have the following output html (example):
So know we can manage the jQuery code that is needed for your custom Ajax add to cart buttons on shop and archive pages…
Try the following that will change the text on your custom Ajax add to cart button on
added_to_cart
WooCommerce jQuery event:Code goes in functions.php file of the active child theme (or active theme). Tested and works.