Ad

Why Required Country Dropdown Field Not Preventing Checkout - WooCommerce

The title might seem a simple fix but it is indicating it is a required field - yet checkout is allowed without an option being chosen and the select option just showing.

I am using Change WooCommerce checkout country field default option displayed label answer code to my previous question, this way:

add_filter( 'woocommerce_form_field_country', 'filter_form_field_country', 10, 4 );
function filter_form_field_country( $field, $key, $args, $value ) {
    // Only in checkout page for "billing" city field
    if ( is_checkout() && 'billing_country' === $key ) {
        $search  = esc_html__( 'Select a country / region…', 'woocommerce' ); // String to search
        $replace = esc_html__( 'Select option to pay correct tax', 'woocommerce' ); // Replacement string
        $field   = str_replace( $search, $replace, $field );
    }
    return $field;
}

add_filter( 'woocommerce_checkout_fields', 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
    $fields['billing']['billing_country']['label'] = __('Are you purchasing as a Company Y/N or from the UK?', 'woocommerce');
    $fields['billing']['billing_country']['required'] = true;

    return $fields;
}

Does anybody see any conflict?

Ad

Answer

In WooCommerce the country dropdown field default option has not an empty value, but "default" as value as you can see in this source code… So you need to add the following, when the selected value is "default", to avoid checkout displaying an error notice:

add_action( 'woocommerce_after_checkout_validation', 'checkout_validation_billing_country', 9999, 2 );
function checkout_validation_billing_country( $data, $errors ){
    // Check for any validation errors
    if ( isset($_POST['billing_country']) && $_POST['billing_country'] === 'default' ){
        $errors->add( 'validation', __('<strong>Billing Country</strong> is a required field. Please select your country.', 'woocommerce') );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Ad
source: stackoverflow.com
Ad