WordPress – Change woocommerce error messages

woocommerceWordpress

I would like to change the text of the error message that occurs on the checkout page when a customer hasn't filled in all the required fields. Currnetly, the message will display EVERY field that needs to be filled in, for example:
"Billing address is a required field.
Billing postal code is q required field.
Email address is a required field.
…"

I would like just ONE message that says "Please fill in the required field." or, if more than one field needs to be filled in "Please fill in the required fields."

Does anyone know how to dy this? My PHP is limited.
Thanks!

Best Answer

Updated Code:

Add this code in function.php file:

function my_woocommerce_add_error( $error ) {
    if (strpos($error,'required') !== false) {
        $error = 'Required';
    }
    return $error;
}
add_filter( 'woocommerce_add_error', 'my_woocommerce_add_error' );

and add this code in notices\error.php file:

<ul class="woocommerce-error">
    <?php 
    $totalReq = count(array_keys($messages, 'Required')); 
    $removeReq = array_diff($messages, ["Required"]);

    if($totalReq > 1){
        echo '<li>Please fill in all the <strong>required</strong> fields.</li>';
    }else{
        echo '<li>Please fill in the <strong>required</strong> field.</li>';
    }
    ?>
    <?php foreach ( $removeReq as $message ) : ?>
        <li><?php echo wp_kses_post( $message ); ?></li>
    <?php endforeach; ?>
</ul>

Hope it will resolve your concern :)

Related Topic