Pawan Kumawat

Show Only One Error Message on Checkout Field Error

How to Show Only One Error Message For WooCommerce Checkout Field?

Their are approximately 7 to 10 default field which are required on WooCommerce checkout field.
In case these all have error then their are so much error in top, you can see in screenshot below. so for removing or we can say replacing all error with only one msg , you can view in screenshot 2.

 

Example :

 

function ShowOneError( $fields, $errors ){
  // if their is any validation errors
  if( !empty( $errors->get_error_codes() ) ) {
    // remove all of Error msg
    foreach( $errors->get_error_codes() as $code ) {
      $errors->remove( $code );
    }
  // our custom Error msg
  $errors->add('validation','There is an error in filed data.');
  } 
}
add_action('woocommerce_after_checkout_validation','ShowOneError',999,2);

 

Please note, that above code removes all types of errors, not only “This Field Is Required” etc.
We can remove them conditionally . For this first we need to type of error.
Types of errors:

  • required-field
  • terms (Terms checkbox)
  • payment

 

So for removing Only “required-field” error:

 

function ShowOneError( $fields, $errors ){
  // if their is any validation errors
  if( !empty( $errors->get_error_codes() ) ) {
    // remove all of Error msg
    foreach( $errors->get_error_codes() as $code ) {
     if( $code == 'required-field') {
      $errors->remove( $code );
     }
    }
  // our custom Error msg
  $errors->add('validation','There is an error in filed data.');
  } 
}
add_action('woocommerce_after_checkout_validation','ShowOneError',999,2);

 

Categories

Related Blogs

WooCommerce: Check if Product ID is in the Cart

To check if a specific product ID is in the cart in WooCommerce, you can use the `woocommerce_before_cart` action hook, which is fired before the cart page is displayed. Here’s how you can achieve this:

How To add custom product data tabs in WooCommerce

To add custom product data tabs in WooCommerce, you can use the woocommerce_product_data_tabs and woocommerce_product_data_panels hooks. These hooks allow you to add new tabs to the product edit page in the WooCommerce admin area. Here’s a step-by-step guide on how to achieve this:

Ajax Add to Cart Quantity on Shop WooCommerce

To enable AJAX add to cart with quantity selectors on the WooCommerce shop page, you’ll need to use JavaScript to handle the AJAX request and update the cart quantity dynamically. Below are the steps to achieve this:

How to hide particular category product on shop

To hide a particular category on the shop page using the `woocommerce_product_query` hook, you can modify the query parameters to exclude the category you want to hide. This approach allows you to customize the product query directly without modifying the main query.