Firefog
Firefog

Reputation: 3174

Woo Commerce Add to cart replace with a message when it hidden on Variable Product

My add to cart button only visible when a variable select other wise it seems to be hidden. Is there any way to show a message instead of hidden add to cart button ? Some thing like "Please choose an option".

not sure : may be this filter can work

woocommerce_single_variation_add_to_cart_button

Upvotes: 0

Views: 941

Answers (1)

SymmetricsWeb
SymmetricsWeb

Reputation: 636

By default, Woocommerce only shows add to cart button once there's an active variation with price,

you'll see on there demo that Add To Cart is hidden when no variation is selected,

Now if you want to add a message when there's no active variation selected, you can hook the message on woocommerce_before_add_to_cart_button or woocommerce_after_add_to_cart_button

e.g.

function add_to_cart_place_holder() {
    global  $post;
    //get_product id
    $product = get_product( $post->ID );
    //if Product is variable add a message
    if( $product->is_type( 'variable' ) ){
        echo '<p class="atc_placeholder">Please choose an option</p>';
    }
}
//Hook product message after Add To cart Button
add_action('woocommerce_after_add_to_cart_button', 'add_to_cart_place_holder');

Your message will appear below the Add To cart button, next thing you want is to hide this message when there's an active variation, so we need to listen the event of variation selection, you can have this code below to give you an idea, its not the best solution but it should work fine, I also use setTimeout function to get the correct css display property after woocommerce modified it,

( function($) {
    // capturing even when select option is change
    $('form.cart').on('change', '.variations select', function() {
        //Add 300ms before checking '.single_variation_wrap' display property
        setTimeout(function () {
            //Show message if add to cart button is hidden
            if ( !$('.single_variation_wrap').is(':visible') ) {
                $('.atc_placeholder').show();
            //hide the mssage when add to cart button is visible
            } else {
                $('.atc_placeholder').hide();
            }
        }, 300);
    });
})(jQuery);

Upvotes: 2

Related Questions