WooCommerce: How to show checkout fields Errors next to the fields

woocommerce responsive

When someone misses a field on the checkout page the error message shows at the top of the page by default, making the customer scroll up and down and putting difficulties to them in the last place we would like to.

The only good part of it is that, at least, in most of the themes the page scrolls up by itself, so you can see the errors.

So, I say, wouldn’t it be better if the error messages were displayed directly next to the field with each error, integrated, so that the user doesn’t have to look at the error list, go through the fields and so on all the time?

The solution

We’re going to solve this problem in two parts, and the first is a bit of functions PHP.

What we will do is look for all the fields that have the required tag and, just before the closing tag, we will add a span with the error.

%MINIFYHTML7f1e326e6ee3077e76a9e218d78e72ba52%
/* Error message next to the field */ add_filter( 'woocommerce_form_field', 'wphelp_error_tag', 10, 4 ); function wphelp_error_tag( $field, $key, $args, $value ) { if ( strpos( $field, '</label>' ) !== false && $args['required'] ) { $error = '<span class="error" style="display:none">'; $error .= sprintf( __( '%s Required field.', 'woocommerce' ), $args['label'] ); $error .= '</span>'; $field = substr_replace( $field, $error, strpos( $field, '</label>' ), 0); } return $field; }

By default it is configured to be display:none, but then we will show it as a visible block through additional CSS of the customizer, in the second step.

Once we show the span on the page only remains to be displayed when the user makes the order but forget to fill in some required field.

This is normally done with a JavaScript validation done by WooCommerce, specifically a CSS class called woocommerce-invalid-required-field, which is applied when a required field is not filled in.

And because WooCommerce already applies this JavaScript that adds the CSS class we don’t have to do it ourselves, we just have to customize the class, like this:

.woocommerce-checkout p.woocommerce-invalid-required-field span.error { color: #ff2a00; display: block !important; font-weight: bold; }

And we get this.

We did not remove the list of errors at the top of the page but it is much clearer for the user which fields they have to complete in order to place the order.

With a few lines of code we greatly improve the usability on the checkout page, and also the accessibility, because on-screen readers will have the error right in the field.

Read this post in Spanish: WooCommerce: Cómo mostrar los errores en el pago junto al campo con error

Click to rate this post!
[Total: 0 Average: 0]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top Skip to content