Categories

Thursday, December 26, 2024
#919814419350 therichposts@gmail.com
WoocommerceWoocommerce HooksWordpress

How to add custom field in woocommerce checkout form and validate it?

How to add download pdf link in woocommerce single product page?

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.