In this post, we’ll learn how to dynamically change the “Add to Cart” button text on single product pages for simple products in WooCommerce. This customization allows you to personalize the button text to better suit your store’s needs.
/**
* Snippet Name: Change "Add to Cart" text dynamically for simple products
* Snippet Author: wpsnippets.dev
*/
// Change "Add to Cart" text dynamically on single product pages for simple products
function wps_custom_add_to_cart_text_script() {
global $product;
if ($product && $product->is_type('simple')) {
?>
<script>
jQuery(document).ready(function($) {
$('.single_add_to_cart_button').click(function() {
var $button = $(this);
$button.text('Added');
});
});
</script>
<?php
}
}
add_action('woocommerce_single_product_summary', 'wps_custom_add_to_cart_text_script', 25);
Code Explanation
- The
wps_custom_add_to_cart_text_script
function globally accesses the$product
object. It checks if the product exists and if it’s a simple product. - If it’s a simple product, a jQuery script is injected into the page, waiting for the document to be ready.
- When the “Add to Cart” button is clicked, the text of the button is changed to ‘Added’ dynamically. You can change Added text to your desired text.
- The function is hooked to the woocommerce_single_product_summary action to execute when rendering single product pages.