Change the alert text on add to cart action without selected variation in Woocommerce

✔ Recommended Answer

WooCommerce has a filter "woocommerce_get_script_data" for all data sent to JavaScript including translated texts.So this is the proper way to change this text :

add_filter( 'woocommerce_get_script_data', 'change_alert_text', 10, 2 );function change_alert_text( $params, $handle ) {    if ( $handle === 'wc-add-to-cart-variation' )        $params['i18n_unavailable_text'] = __( 'Your new alert text', 'domain' );    return $params;}

If WooCommerce change this translation, you will have a problem with the accepted answer, your condition will be false.

Source: stackoverflow.com

Answered By: Keylies

Method #2

To change the alert text on the "add to cart" action without selecting a variation in Woocommerce, you can use the following code snippet:

php
function change_no_variation_text() { global $product; $product_type = $product->get_type(); if ( 'variable' === $product_type ) { $default_text = esc_html__( 'Please select options before adding this product to your cart.', 'woocommerce' ); $updated_text = esc_html__( 'Please choose a variation before adding this product to your cart.', 'woocommerce' ); ?> <script type="text/javascript"> jQuery(document).ready(function($) { $('form.variations_form').on('click', 'button.single_add_to_cart_button', function() { if ( ! $('input[name=variation_id]').val() > 0 ) { alert("<?php echo $updated_text; ?>"); return false; } }); }); </script> <?php } } add_action( 'woocommerce_before_add_to_cart_button', 'change_no_variation_text' );

This code adds a script to the "woocommerce_before_add_to_cart_button" action that listens for a click on the "add to cart" button within a "variations_form" element. If no variation has been selected (i.e., the "variation_id" input field is empty), the script displays an alert with the updated text, and prevents the default behavior of adding the product to the cart.

You can customize the text by changing the values of the $default_text and $updated_text variables in the code.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755