WooCommerce: always show the "add to cart" button even before choosing a choice

WooCommerce doesn’t generate the Add to Cart button on a single product’s product variable page until one option is selected. If two options are required, but only one is selected, the WC still generates a button, but clicking on it causes an error message asking you to select all options.

Besides the fact that I do not understand this logic (why use the error message after sending for the second option and another solution - the button without sending - for the first?), Is there a way to show the "add to cart" button at any time, with a message about error after submitting if all options have not been selected?

+4
source share
2 answers

This should complete the task:

add_action( 'woocommerce_before_add_to_cart_button', function(){
    // start output buffering
    ob_start();
} );

add_action( 'woocommerce_before_single_variation', function(){
    // end output buffering
    ob_end_clean();
    // output custom div
    echo '<div class="single_variation_wrap_custom">';
} );

In fact, I intercepted (inside the template file single-product/add-to-cart/variable.php) an HTML tag <div class="single_variation_wrap" style="display:none;">that is affected by javascript of the user's choice and replaced with <div class="single_variation_wrap_custom">one that is not.

+9
source

I also think that there will be a much higher conversion rate if the add to cart button is always visible. my task: always show the button. if no selection is selected, display an error message ("select an option") by clicking. this is how I DECIDED IT. All you need to do is edit functions.php functions: For this, I use the second "fake" button. so first we insert this button:

function wc_custom_addtocart_button(){
    global $product;
    ?>
    <a href="#" class="btn btn-primary btn-block placeholder_button"><?php echo $product->single_add_to_cart_text(); ?></a>
    <?php
}
add_action("woocommerce_before_add_to_cart_button","wc_custom_addtocart_button");

Then we switch the visibility using custom js code:

function run_js_code(){
    if (get_post_type() == "product"):
    ?>
    <script>   
    jQuery(document).ready(function($) {
        // use woocommerce events:
        $(document).on( 'found_variation', function() {
            $(".single_add_to_cart_button").show();
            $(".placeholder_button").hide();
        });
        $(".variations_form").on( 'click', '.reset_variations', function() {
            $(".single_add_to_cart_button").hide();
            $(".placeholder_button").show();
        });
        // display alert when no variation is chosen:
        $(".placeholder_button").click(function(e){
            e.preventDefault();
            alert("Please choose a product variation!");
        });
    });
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'run_js_code' );

i css:

.single_add_to_cart_button { display: none; }

, woocommerce .

+1

All Articles