Search code examples
jquerywordpresswoocommerceproduct-variations

Don't allow users to deselect variation in WooCommerce


I don't want to allow users to not select any variations of a product in WooCommerce. At the moment, I always add a default variation to any product. But the user can deselect the variaton.

Is there any way to prevent that?


Solution

  • Your current issue scenario: enter image description here

    After adding the below code, it will make your default variation selected and users will not have any option to select "Choose option". As here below code will remove that select option. So first option will be shown as option value every time.

    add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );
    function filter_dropdown_option_html( $html, $args ) {
        $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );
        $show_option_none_html = '<option value="">' . esc_html( $show_option_none_text ) . '</option>';
    
        $html = str_replace($show_option_none_html, '', $html);
    
        return $html;
    }
    

    This is to remove clear button:

    add_filter( 'woocommerce_reset_variations_link', '__return_empty_string', 9999 );
    

    After apply above code, result will be enter image description here

    Please let me know if it's not work in your scenario.

    Thanks.