Hello to all and welcome on therichpost.com. In this post, I will tell you, How to add custom field in woocommerce checkout form and validate it?
Woocommerce is the best ecommerce platform and famous wordpress plugin.
I just added select options custom fields with select2 functionality.
Here is the working hook and you just need to add this into your theme’s functions.php file:
/////#Add New Field#/////
add_action( 'woocommerce_after_checkout_billing_form', 'add_extra_fields_after_billing_address',1,1)
function add_extra_fields_after_billing_address() {
_e( "Referral:", "add_extra_fields");
?>
<br>
<select name="add_referral" class="add_referral">
<option value="">Select Referral</option>
<option value="Google">Google</option>
<option value="Facebook">Facebook</option>
<option value="Other company">Other company</option>
</select>
<script>
jQuery(document).ready(function($){
$(document).ready(function() {
$('.add_referral').select2();
});
})
</script>
<?php
}
/////#Add New Field Validation#/////
add_action('woocommerce_after_checkout_validation', 'add_validate',10,2);
function add_validate($data,$errors) {
if ( isset( $_POST['add_referral']) && empty( $_POST['add_referral'])){
$errors->add( 'validation', __( "<strong>Referral</strong> is a required field." ));
}
}
If you have any related to this post or any other query related to woocommerce then feel free to ask.
Jassa
Thank you
