Set a unique validation error notice in Woocommerc

2019-05-30 21:50发布

Billing fields in Woocommerce checkout page and my account page shows individual error if the required fields are empty. Well, if all fields are empty, all errors for those empty fields will be shown like:
- First name is a required field
- Last name is a required field
- Street address is a required field
and so on…

I want to display only one error if all the required fields are empty, like “ERROR: All fields are empty. Please fill in all required fields to place order.” Well I somehow solved this problem on checkout page with the code below:

add_action( 'woocommerce_after_checkout_validation', 'show_one_err', 9999, 2);
function show_one_err( $fields, $errors ){
    // if any validation errors
    if( !empty( $errors->get_error_codes() ) ) {

        // remove all of them
        foreach( $errors->get_error_codes() as $code ) {
            $errors->remove( $code );
        }

        // add our custom one
        $errors->add( 'validation', 'Please fill in all required fields to place order.' );
    }
}

My problem right now is how to apply these changes in Woocommerce My Account page - billing address and also in My Account - account details tab. My sole purpose of these changes is to have a consistent error notice in all Woocommerce fields (Please see attach images below).

Checkout page

Checkout page

My Account - billing address

My Account - billing address

My Account - account details

My Account - account details

1条回答
来,给爷笑一个
2楼-- · 2019-05-30 22:27

To replace all fields validation errors by a unique custom one from Account Billing and Shipping Address, and also Account details, you will use the following hooked function that uses two validation hooks:

add_action( 'woocommerce_save_account_details_errors', 'account_validation_unique_error', 9999 ); // Details
add_action( 'woocommerce_after_save_address_validation', 'account_validation_unique_error', 9999 ); // Adresses
function account_validation_unique_error(){
    $notices = WC()->session->get( 'wc_notices' ); // Get Woocommerce notices from session

    // if any validation errors
    if( $notices && isset( $notices['error'] ) ) {

        // remove all of them
        WC()->session->__unset( 'wc_notices' );

        // Add one custom one instead
        wc_add_notice( __( 'Please fill in all required fields…', 'woocommerce' ), 'error' );
    }
}

Code goes in function.php file of your active child theme (active theme). Tested and works.

enter image description here

Related: Set a unique validation error notice in Woocommerce checkout page

查看更多
登录 后发表回答