How to customize “Add to Card” Button Text
Dec 30, 2022
0
Nikita
Full-Stack developer
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages function custom_add_to_cart_price( $button_text, $product ) { // Variable products if( $product->is_type('variable') ) { // shop and archives if( ! is_product() ){ $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) ); return $button_text . ' - From ' . strip_tags( $product_price ); } // Single product pages else { return $button_text; } } // All other product types else { $product_price = wc_price( wc_get_price_to_display( $product ) ); return 'BUY THIS ITEM FOR ' . strip_tags( $product_price ); } }
This code adds two filters to customize the text of the “Add to Cart” button in WooCommerce. The first filter applies to the Shop page and other archive pages, while the second filter applies to single product pages.
The function ‘custom_add_to_cart_price’ accepts two arguments: ‘$button_text’ and ‘$product’.
For variable products (products with multiple options, such as size or color), the function first checks if the current page is a single product page. If it is, the function returns the default ‘$button_text’. If it’s not a single product page, the function gets the price of the first variation of the product and appends it to the ‘$button_text’, preceded by the text “From”.
For all other product types, the function gets the price of the product and appends it to the $button_text, preceded by the text “BUY THIS ITEM FOR”.
Finally, the modified ‘$button_text’ is returned by the function. This modified text will be used as the text of the “Add to Cart” button in place of the default text.