WooCommerce: Display Required Field Errors “Inline” @ Checkout

 If you’re familiar with the upcoming Gutenberg editor, you’ll know there have been a million doubts in regard to accessibility. So, accessibility matters – and WooCommerce has a few issues as well.

One interesting accessibility fix is the error notification system on the checkout page. Yes, the missing fields error show on top of the page when trying to place an order, but once you scroll down to fill them out again you might need a reminder of which field is missing without having to scroll back up to check the error.

This is quite difficult to explain, so take a look at the screenshot. The suggestion here is to also add “inline” error notifications (“XYZ is a required field“) right above each field, so that the user knows exactly what to do. So, let’s see how it’s done.

Displaying inline “required field” errors @ WooCommerce Checkout

Snippet Part 1 (PHP): Print Required Field Errors Inline @ WooCommerce Checkout

The first part is a PHP workaround. We basically go searching for all those fields that have a label and are required, and just before the closing label tag we add a span containing the error.

By default, this is set as display:none, which will be displayed as block and therefore made visible via CSS later on (Snippet 2).

/**
 * @snippet       Add Inline Field Error Notifications @ WooCommerce Checkout
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=86570
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_form_field', 'bbloomer_checkout_fields_in_label_error', 10, 4 );
 
function bbloomer_checkout_fields_in_label_error( $field, $key, $args, $value ) {
   if ( strpos( $field, '</label>' ) !== false && $args['required'] ) {
      $error = '<span class="error" style="display:none">';
      $error .= sprintf( __( '%s is a required field.', 'woocommerce' ), $args['label'] );
      $error .= '</span>';
      $field = substr_replace( $field, $error, strpos( $field, '</label>' ), 0);
   }
   return $field;
}

Snippet Part 2 (CSS): Display Required Field Errors Inline @ WooCommerce Checkout

Now that those spans are printed on the page, we need to display them in case users go place the order but forget to fill out a required field.

This is usually done via JavaScript validation… but WooCommerce already does that for us 🙂

WooCommerce JS adds a CSS class called “woocommerce-invalid-required-field” to a required field that is not filled out.

Each field will be getting this class and generate an error. So, thankfully, we need no JS for showing those hidden spans, we can simply target the class!

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

No comments:

Post a Comment

Free Shipping Threshold @ Cart Page