Set a unique validation error notice in Woocommerce My Account Addresses and Account Details

喜欢而已 提交于 2019-12-23 03:07:14

问题


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

My Account - billing address

My Account - account details


回答1:


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.

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



来源:https://stackoverflow.com/questions/53279751/set-a-unique-validation-error-notice-in-woocommerce-my-account-addresses-and-acc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!