How to Make WooCommerce Order Comments Required

Make WooCommerce Order Comments Required

In a recent project, I was required to make WooCommerce order comments required since we were using a PayPal express checkout plugin that was customized to populate the shipping details from PayPal.

I was required to add a new custom field along with the order_comments field to allow users to add the title of the event and use the order comment as the description of the event.

Create Custom WooCommerce Field

To add an extra custom title field I quickly added a WooCommerce field using the following code :

<h3><?php _e( 'Add Events Details', 'text-domain' ); ?></h3>

<?php 
woocommerce_form_field( 'event_details', 
       array(
	   'type'        => 'text',
	   'required'    => true,
	   'label'       => 'Event Title',
	   'description' => 'Please enter your Event Title',
	 ), 
   $checkout->get_value( 'event_details' ) );
}

?>

Create Order Comments Field

After adding the custom title field we needed to add the order comment that is not available in the confirm order in the PayPal checkout plugin.

The following is the code to add the order_comment or order_notes :

<?php 

if ( version_compare( WC_VERSION, '3.0', '<' ) ) {

    $fields = WC()->checkout->checkout_fields['billing'];

    } else {

	$fields = WC()->checkout->get_checkout_fields( 'billing' );
}

  woocommerce_form_field( 
		  'order_comments', 
		  $fields['order_comments'],
		  WC()->checkout->get_value( 'order_comments')
  ); 

Make WooCommerce Order Comments Required

After creating the order comments you may want to make it required such that the users have to add some text before they can place the order.

In this case, you will use a WooCommerce validation hook that checks if the order comments or order notes are empty if not the user can proceed to place the order.

To make this order comments field required in WooCommerce you need to add the following code to the functions.php file of your active theme:

  /**
   *  Code Snippet should be added to the functions.php to make WooCommerce order comments required 
   */ 
   
  add_action('woocommerce_after_checkout_validation', 'njengah_make_woocommerce_order_comments_required');

  function njengah_make_woocommerce_order_comments_required() {
  
            // Check if set, if its not set add an error.
			
            if ( ! $_POST['order_comments'] )
			
                wc_add_notice( __( 'Please add delivery instructions' ), 'error' );
  }

Alternative Way to Make WooCommerce Order Comments Required

If you don’t wish to use the code added to the functions.php, you can use control the behavior of the WooCommerce checkout fields plugin.

Similar Articles

 

Comments are closed.