Let’s say you have a certain product that you need to capture additional information for at checkout. Using WooCommerce we can add fields to the checkout based on nearly any conditional matches.
For this tutorial we will be using the premise of a book seller. Let’s say that the store owner wants to add an option at checkout for the user to choose whether they would like the book inscribed with a message from the author.
Adding Custom Fields to Checkout
WooCommerce is filled with many useful hooks to tie into with our code. The checkout action we will be using for this tutorial is woocommerce_after_order_notes which will allow us to add our custom fields directly below the “Order Notes” field in the checkout form. If you would like your fields to display elsewhere there are a number of additional hooks you can use such as woocommerce_after_shipping_calculator and woocommerce_after_shop_loop.
Within the following function we will check what items the user has in their cart by looping through their products and flagging a variable as true or false. If the variable is false the fields will not output, if it is true and the specific product is in the cart will will output our fields. Here’s the code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
/** * Add the field to the checkout **/ add_action( 'woocommerce_after_order_notes', 'wordimpress_custom_checkout_field' ); function wordimpress_custom_checkout_field( $checkout ) { //Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID) $book_in_cart = wordimpress_is_conditional_product_in_cart( 117 ); //Book is in cart so show additional fields if ( $book_in_cart === true ) { echo '<div id="my_custom_checkout_field"><h3>' . __( 'Book Customization' ) . '</h3><p style="margin: 0 0 8px;">Would you like an inscription from the author in your book?</p>'; woocommerce_form_field( 'inscription_checkbox', array( 'type' => 'checkbox', 'class' => array( 'inscription-checkbox form-row-wide' ), 'label' => __( 'Yes' ), ), $checkout->get_value( 'inscription_checkbox' ) ); woocommerce_form_field( 'inscription_textbox', array( 'type' => 'text', 'class' => array( 'inscription-text form-row-wide' ), 'label' => __( 'To whom should the inscription be made?' ), ), $checkout->get_value( 'inscription_textbox' ) ); echo '</div>'; } } /** * Check if Conditional Product is In cart * * @param $product_id * * @return bool */ function wordimpress_is_conditional_product_in_cart( $product_id ) { //Check to see if user has product in cart global $woocommerce; //flag no book in cart $book_in_cart = false; foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; if ( $_product->id === $product_id ) { //book is in cart! $book_in_cart = true; } } return $book_in_cart; } |
Make sure you update the product ID to whichever product you are adding the conditional field for. You can update this to test for multiple products, a category of products or variation.
Now check out the cart page and you should see the fields added below the checkout.
Hide the Inscription Text Field with CSS
We need to hide the inscription text field from the user until they have chosen the inscription option. This is easy thankfully with some simple CSS. Add this to your theme’s stylesheet:
|
1 |
.inscription-text { display:none; } |
Slide Toggle the Field Based on the User’s Choice
Now, if the user selects the “Yes” checkbox we want to slide the inscription text field down. If they uncheck the field we will slide it up. Let’s use some simple jQuery to do this:
|
1 2 3 |
$('.inscription-checkbox input[type="checkbox"]').on('click', function () { $('.inscription-text').slideToggle(); }); |
Here’s what my checkout fields look like with some additional styling.
Not Toggled:

Toggled:

Tip: Check out the woocommerce_form_field function within WooCommerce to modify the fields to a textarea, select, etc.
Save the New Checkout Fields Upon Successful Order
Now that our fields are displaying properly we need to save them to the order meta when the order goes through. We will again use a WooCommerce hook to do this called woocommerce_checkout_update_order_meta.
Add the following code below the function provided above and update with your necessary modifications:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/** * Update the order meta with field value **/ add_action( 'woocommerce_checkout_update_order_meta', 'wordimpress_custom_checkout_field_update_order_meta' ); function wordimpress_custom_checkout_field_update_order_meta( $order_id ) { //check if $_POST has our custom fields if ( $_POST['inscription_checkbox'] ) { //It does: update post meta for this order update_post_meta( $order_id, 'Inscription Option', esc_attr( $_POST['inscription_checkbox'] ) ); } if ( $_POST['inscription_textbox'] ) { update_post_meta( $order_id, 'Inscription Text', esc_attr( $_POST['inscription_textbox'] ) ); } } |
Now test an order out and you should see our custom field data in the order’s post meta:

Now that the data is attached to the post you can do whatever you like with it.
Add the Custom Field Data to Order Emails
Most likely the shop owner is notified of orders via email. What we want to do is send our custom field data along with that email so they can fulfill the order accordingly.
We are going to be using a filter called woocommerce_email_order_meta_keys to send our data along with the email. Again, we will first check the the order does contain the product because we don’t want to clutter up the email with blank custom fields.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Add the field to order emails **/ add_filter( 'woocommerce_email_order_meta_keys', 'wordimpress_checkout_field_order_meta_keys' ); function wordimpress_checkout_field_order_meta_keys( $keys ) { //Check if Book in Cart $book_in_cart = wordimpress_is_conditional_product_in_cart( 117 ); //Only if book in cart if ( $book_in_cart === true ) { $keys[] = 'Inscription Option'; $keys[] = 'Inscription Text'; } return $keys; } |
Now when an order goes that contains our specific product, in this case a book, our fields will display:

Conditional Checkout Fields: Oh the Potential
With conditional checkout fields in WooCommerce there is a lot of potential use cases. For instance, you can ask a user to sign up to a specific mailing list based on their product choice, ask for additional shipping requirements or special handling questions, or request additional information from the user. The system is setup to be very flexible, you just have to know how to use it.
If you have any comments, feedback or contributions please use the comments below.
104 Responses to “How to Create Conditional Checkout Fields in WooCommerce”
Joseph K. Wasden
Spot on Devin! very helpful.
In this example, the conditional checkout field is contingent on products. Is there an easy way to make it conditional on the user role?
Thanks,
Joe
Devin Walker
Hmm, I haven’t looked into it based on User Roles. What does that checkout flow look like? Are most users not-logged it when they checkout? If they are logged in then you want to capture their user role and display certain data?
Joseph K. Wasden
“If they are logged in then you want to capture their user role and display certain data?”
Exactly. Really, I’m trying to customize the contents of the confirmation email when a purchase comes from a specific role. Since check out information is included in the email this seemmed like a possible solution.
Paolo
Hi Devin,
i really know where did you add the jquey code.
Thanks,
Paolo
Kevin
How would I modify this to test for a category? I thought I had it, but then it broke my gateway form.
Aleksey Napolskih
here is my way of checking if the product is in category:
/**
* Check if Conditional Product is In cart
* @param $cat_id
* @return bool
*/
function is_conditional_product_in_cart( $cat_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag not in cart
$in_cart = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values[‘data’];
$cats = all_cat_classes($_product);
foreach ($cats as $values) {
//product is in cart!
if($values === $cat_id)
$in_cart = true;
}
}
return $in_cart;
}
# Will return all categories of a product, including parent categories (modified to return only the parent category)
function all_cat_classes($post) {
$catz = array();
$terms = get_the_terms($post->id, ‘product_cat’);
// foreach product_cat get main top product_cat
foreach ($terms as $cat) {
$catz = get_parent_terms($cat);
//$cats .= (strpos($cats, $cat->slug) === false ? $cat->slug.” ” : “”);
}
return $catz;
}
function get_parent_terms($term) {
if ($term->parent > 0) {
$term = get_term_by(“id”, $term->parent, “product_cat”);
if ($term->parent > 0) {
get_parent_terms($term);
} else return $term;
}
else return $term;
}
Schalk
Hi,
I copied your code to my functions,php.
Say my Category is called Tickets and the id is 13, where should i add this?
Many thanks
Aleksey Napolskih
In this case you call the function like this
$in_cart = is_conditional_product_in_cart(13);
Schalk
Hi,
Not sure where to add that line, in your code or that of Devin…
I am using a 1file plugin which adds extra fields for attendees to the checkout field. The problem is these fields are added even when a non ticket product is bought. I want this to only show when a product in the cart is in the “ticket” category.
Schalk
I know this is asking a lot, but just maybe it is simple and easy for you…
This is the one file plugin / extension
0) {
echo “”; //close the Billing Address section to create new group of fields
echo “”; //automatically be closed from 2 Billing Address’s div –
echo ”.__(‘All Event Attendees and/or clients who are ordering DVDs, please add your name and email again.’).”;
for($n = 1; $n ‘text’,
‘class’ => array(‘form-row form-row-first’),
‘label’ => __(‘Name’),
‘placeholder’ => __(‘name’),
‘required’ => true,
), $checkout->get_value( ‘attendee_name_’.$n ));
woocommerce_form_field( ‘attendee_email_’.$n, array(
‘type’ => ‘text’,
‘class’ => array(‘form-row validate-email’),
‘label’ => __(‘Email’),
‘placeholder’ => __(’email’),
‘required’ => true,
), $checkout->get_value( ‘attendee_email_’.$n ));
woocommerce_form_field( ‘attendee_phone_’.$n, array(
‘type’ => ‘text’,
‘class’ => array(‘form-row form-row-last’),
‘label’ => __(‘Phone’),
‘placeholder’ => __(”),
), $checkout->get_value( ‘attendee_phone_’.$n ));
}
echo ”
#attendee_details .form-row {
float: left;
margin-right: 2%;
width: 31%;
}
#attendee_details .form-row-last {
margin-right: 0;
}
“;
}
//echo “Attendees: ” . $attendee_count;
}
/**
* Process the checkout
**/
add_action(‘woocommerce_checkout_process’, ‘wt_attendee_fields_process’);
function wt_attendee_fields_process() {
global $woocommerce;
$attendee_count = wt_count_attendees();
for($n = 1; $n add_error( __(‘Please complete the attendee details.’) );
}
}
/**
* Update the order meta with field value
**/
add_action(‘woocommerce_checkout_update_order_meta’, ‘wt_attendee_update_order_meta’);
function wt_attendee_update_order_meta( $order_id ) {
$attendee_count = wt_count_attendees();
for($n = 1; $n cart->get_cart())>0) :
foreach ($woocommerce->cart->get_cart() as $item_id => $values) :
$_product = $values[‘data’];
if ($_product->exists() && $values[‘quantity’]>0) :
if (get_post_meta($_product->id, ‘_tribe_wooticket_for_event’) > 0)
$attendee_count += $values[‘quantity’];
endif;
endforeach;
endif;
return $attendee_count;
}
}
?>
Aleksey Napolskih
Hi. Let me try to help out. The plugin code is incomplete so it’s hard to tell you exactly. Please use http://pastebin.com and post the link.
But the basic idea is you paste my code into the functions.php and then modify your plugin code (you could actually paste my code in the plugin code itself while you are at it – clean up the functions.php in this case to avoid duplications)
The idea is you check if the product is part of the root category with ID 13
$in_cart = is_conditional_product_in_cart(13);
and then you render additional fields if the above is true
if($in_cart) {
call to your function that renders those additional fields…
}
Aleksey Napolskih
Thanks very much Devin! That helped me a lot.
Devin Walker
Glad it helped!
jazzfanatic
Well, I got stuck on the jQuery in the third step. I’m using Thesis rather than a WP theme, and I know where to put the actions and functions, but I’m not sure where the jQuery is supposed to go. I have it as a called script in my Head Scripts as per this link – http://www.freezecoders.com/2013/12/how-to-use-custom-jquery-code-in-wordpress-thesis.html – but it’s not working. Help?
(Thank you so much for sharing this info!)
Devin Walker
Yeah the jQuery should work fine in the head. Did you test it with the alert in the example look to make sure it’s working? Does the jQuery selector match the element you wish to show and hide?
jazzfanatic
Yep, tested it with the alert, and changed the selector to match my modified functions. Everything *seems* to be right, which is why I was confused.
In the head, I have it as (with three text fields I’m trying to hide):
$(‘.layaway-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.initial-text’).slideToggle();
$(‘.monthly-text’).slideToggle();
$(‘.date-text’).slideToggle();
});
alert(‘Custom jquery Code has been executed’);
});
jQuery is really not my thing, so I’m wondering if I just have bad syntax in the head somewhere?
Devin Walker
This script is inserted AFTER jQuery, correct? You’re fields are on the checkout screen but simply not showing/hiding as expected? The jQuery part should be the easier part to configure with the setup.
jazzfanatic
Yep, the fields are there, just not hiding when the box is unchecked (default is set to unchecked). The jQuery part definitely *sounded* easier — hence my frustration. 🙂
tex88
In WP, sometimes jQuery needs to use ‘jQuery’ instead of the ‘$’. So instead of this-
$(‘.date-text’).slideToggle();
you’d have this-
jQuery(‘.date-text’).slideToggle();
Benjamin F.
Did you ever figure this out? Currently working on the same exact issue on checkout page.
jazzfanatic
There most likely is indeed a script conflict, but I just don’t know enough to fix it. I kind of think it’s a problem with Thesis. Sorry, wish I were more help, but we ended up going a different route altogether.
Benjamin F.
It’s all good. It seems like the “Create an Account” checkbox uses the logic I want.
I’m going to keep tinkering and let you know if I find anything.
tex88
How can the conditional (toggled) field be REQUIRED, but of course only if it’s visible?
Devin Walker
You can use jQuery to do that… if the field is visible check to see if it has a value, if it doesn’t then prevent the form from submitting and display an error message.
simon boakes (edition1)
Hi,
I have the code below running and it hides the text box, I am trying to get the text box when displayed be a required field though please and do not see how in the current responses?
$(‘.inscription-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.inscription-text’).slideToggle();
});
Scott DeLuzio
In your example, if someone ordered two (or more) books, and wanted a different inscription in each, how would you check the quantity of books ordered, and then display the correct number of fields?
Devin Walker
Excellent question. You would have to check the user’s cart object to see how many of the specific product (in this case a book) they have added. Then you would look through this number to output the appropriate number of inscription fields. The reveal and hide logic would also need to be updated to account for multiple fields. This adds a level of complexity that may be a good idea for a follow up article.
Scott DeLuzio
Thanks. I’ve been trying to accomplish this for a golf tournament checkout using Woocommerce. At most someone would be paying for four golfers (everyone in their foursome), but they could also be paying for anywhere between 1-4 people. So I want to show the correct number of fields for the customer to enter the names of each person they are paying for. I have explained what I have so far here: http://stackoverflow.com/questions/22824303/woocommerce-get-quantity-of-specific-items-in-cart-on-checkout-page
Schalk
Hi, Ive been trying for days, and had help from Aleksey Napolskih, but still battling.
How do I go about making the attached code / dropbox link, to show confitional if a certain product with say id 232 is in the cart?
https://www.dropbox.com/s/bvj8xrq3asirxmv/wootickets-attendees-list.php
many thanx
schalk
Anonymous Coward
Thanks for this excellent tutorial. While there are paid plugins that make this easier, this tutorial is great for those that like to “bake in” functionality to their site theme. I was able to collapse multiple checkboxes into a single field in the order meta which was very nice and something I don’t feel like spending money to find out if it’s possible in some “Pro” plugin version.
Vahid
I hope you can help me solve this problem:
How to conditionally hide some of the checkout fields when there are just virtual products in the cart?
I’d like to hide the below fields when there are just virtual products in the cart:
billing_company
billing_address_1
billing_address_2
billing_city
billing_postcode
billing_country
billing_state
It’s obvious that I need all the fields when there are both virtual and non-virtual products in the customer’s cart.
Carl VanderLaan
How do you update this to use multiple variation ids as the condition?
Benjamin F.
Did you ever find a solution with multiple? I’d love to be able to hide multiple forms.
Carl VanderLaan
No, I posted something a question on StackOverflow: http://stackoverflow.com/questions/26270781/woocommerce-variable-checkout-fields-base-on-variable-id but no one ever commented.
Carl VanderLaan
to do multiple product ids, you should be able to do the following:
$book_in_cart = wordimpress_is_conditional_product_in_cart( 117 || 118 || 210);
I’m trying to figure out how you use the variation ids.
Carl VanderLaan
Looks like someone gave an answer that should help you for product ids. Check it out here: http://stackoverflow.com/questions/26413738/woocommerce-variable-checkout-fields-base-on-variable-id
Imran
if you only need this with multiple ID’s (not variations) you can use || in this line
if (( $_categoryid === 14 ) || ( $_categoryid === 16 )) {
gianni
It’s possible to create a custom field that depends on the gateway choice?
For example, if I choose BACS a field named ONE will show, while if I choose another gateway ONE field disappears and a field named TWO appears…
Annette Voelckner
Hi gianni, I am looking for that right now. Did you figure it out?
aranuir
Not yet. And you? 😉
Mohammed Saimon
Hello, this is saimon from gadgetghor.com . I use woo-commerce but now I am unable to do this things..
regards
Saimon
online shopping in Bangladesh
olivier
Hi tanks for the snippet, I’m also trying to adapt this for product categorie instead of product ID but i can’t achieve it. Could you help ? thanks a lot.
Arial Burnz
Hello! Please forgive me if this was covered, but I can’t seem to find the information in this article or the comments. What file is/files are being modified with the above code? I would hate to add all this information to the wrong file. Thank you!!
kevvs
Put the code in your themes function.php
Arial Burnz
Thank you!!!!!!!
Laura
This is exactly the issue I’m having. How did you solve it?
Arial Burnz
Unfortunately, I know just enough code to make me dangerous and I could only get the code to extra fields for ONE product. I have no idea how to apply it to more than one product.
You copy the above snippet and paste it into your “functions.php” file. Make sure you paste it right BEFORE the “?>”
Here’s how I modified the code for my particular product, and you’ll see I got daring and added a few options/fields.
———–
/**
***********************************************************************************************
* WooCommerce Modifications – Add custom fields to the checkout for a specific item *
***********************************************************************************************
**/
add_action( ‘woocommerce_after_order_notes’, ‘wordimpress_custom_checkout_field’ );
function wordimpress_custom_checkout_field( $checkout ) {
//Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID)
$book_in_cart = wordimpress_is_conditional_product_in_cart( 385 );
//Book is in cart so show additional fields
if ( $book_in_cart === true ) {
echo ” . __( ‘***FOR AUTHORS SHARING A TABLE***’ ) . ‘Looks like you are purchasing the option to share your table with another author. Please provide the REAL NAME, PEN NAME and E-MAIL ADDRESS of the author with whom you are sharing a table. Thank you!’;
woocommerce_form_field( ‘realname_textbox’, array(
‘type’ => ‘text’,
‘class’ => array( ‘realname-text form-row-wide’ ),
‘label’ => __( ‘Real Name:’ ),
), $checkout->get_value( ‘realname_textbox’ ) );
woocommerce_form_field( ‘penname_textbox’, array(
‘type’ => ‘text’,
‘class’ => array( ‘penname-text form-row-wide’ ),
‘label’ => __( ‘Pen Name:’ ),
), $checkout->get_value( ‘penname_textbox’ ) );
woocommerce_form_field( ’email_textbox’, array(
‘type’ => ‘text’,
‘class’ => array( ’email-text form-row-wide’ ),
‘label’ => __( ‘E-Mail:’ ),
), $checkout->get_value( ‘penname_textbox’ ) );
echo ”;
}
}
/**
* WooCommerce Modifications – Check if Conditional Product is In cart
*
* @param $product_id
*
* @return bool
*/
function wordimpress_is_conditional_product_in_cart( $product_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag no book in cart
$book_in_cart = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values[‘data’];
if ( $_product->id === $product_id ) {
//book is in cart!
$book_in_cart = true;
}
}
return $book_in_cart;
}
/**
* Update the order meta with field value
**/
add_action( ‘woocommerce_checkout_update_order_meta’, ‘wordimpress_custom_checkout_field_update_order_meta’ );
function wordimpress_custom_checkout_field_update_order_meta( $order_id ) {
if ( $_POST[‘realname_textbox’] ) {
//It does: update post meta for this order
update_post_meta( $order_id, ‘Real Name’, esc_attr( $_POST[‘realname_textbox’] ) );
}
if ( $_POST[‘penname_textbox’] ) {
update_post_meta( $order_id, ‘Pen Name’, esc_attr( $_POST[‘penname_textbox’] ) );
}
if ( $_POST[’email_textbox’] ) {
update_post_meta( $order_id, ‘E-Mail’, esc_attr( $_POST[’email_textbox’] ) );
}
}
/**
* WooCommerce Modifications – Add the custom fields to order emails
**/
add_filter( ‘woocommerce_email_order_meta_keys’, ‘wordimpress_checkout_field_order_meta_keys’ );
function wordimpress_checkout_field_order_meta_keys( $keys ) {
//Check if Book in Cart
$book_in_cart = wordimpress_is_conditional_product_in_cart( 385 );
//Only if book in cart
if ( $book_in_cart === true ) {
$keys[] = ‘Real Name’;
$keys[] = ‘Pen Name’;
$keys[] = ‘E-Mail’;
}
return $keys;
}
?>
———-
I hope that helps. Let me know if you have any questions, but this would really be the blind leading the blind. LOL
Good luck!
Laura
Yeah, I’d gotten that far as well. Same thing…I know just enough to be dangerous, not enough to figure some things out. I need it to apply to an array of items instead of just one. But thank you. I appreciate it.
Jones
If anyone else needs to figure out how to add multiple products, here it is:
Change:
$book_in_cart = wordimpress_is_conditional_product_in_cart( 385 );
to:
$book_in_cart = wordimpress_is_conditional_product_in_cart( array( 385, 386, 387) );
(etc)
followed by changing:
if ( $_product->id === $product_id ) {
to:
if ( in_array($_product->id, $product_id) )
Kristy Stevens
I couldn’t get thi to work for multiple products – I get an array error when I change
if ( $_product->id === $product_id ) {
to:
if ( in_array($_product->id, $product_id) )
Arial Burnz
YAY!!!!!! I did it!!! Thank you so very much for your help and this wonderful tutorial!!!! MWAH!!! Hi Five!!
Arial Burnz
One more question: My client now wants me to modify multiple products. How do I add the multiple products? Can I just list them as commas? Like this?
$book_in_cart = wordimpress_is_conditional_product_in_cart( 226, 227 );
Or would I put a new line for each product?
$book_in_cart = wordimpress_is_conditional_product_in_cart( 226 );
$book_in_cart = wordimpress_is_conditional_product_in_cart( 227 );
And I have different custom fields for each product, so I am assuming I would enter separate arrays for those, like what was listed for “woocommerce_form_field(…”
Thank you!!!
kevvs
functions.php*
drahcir2002
Thanks so much for the code. I can’t get this to work with the if book_in_cart statement in function wordimpress_checkout_field_order_meta_keys. if I remove the check book_in_cart, it works fine. But when I use the check book_in_cart it does not add the information to the email. Anyone else have this problem?
John
Hi Devin, I’ve been working on similar to your example, I have two fields that on their own work as expected but when both are present they almost seem to be acting as one or only my first condition runs, is this something you’ve run into before?
Chris
Hi there….Very interesting post.. I have one question, because I’m facing difficulties with the jQuery function as the input form doesn’t show up when i click on checkbox. Where should i add this jQuery code? Is there any additional code that i should add in order to show this input form?
Devin Walker
You may have to change the selector to show/hide the form input that you want to display conditionally. This code would typically go in a custom functionality plugin JS file or output via your functions.php in your theme (less recommended)
Gabrielle
Hi,is it possible to add 2 number fields to product page, validate price from those fields and save their values on order page? I try many plugins/forms without result ;/
Devin Walker
This is definitely possible! Best bet is to custom code it for your particular needs.
gabrielle
@Devin, Hi again, i read also this tutorial:
http://wisdmlabs.com/blog/add-custom-data-woocommerce-order/#comment-270770
but something goes wrong with my code, could you,please look at my functions.php file?
Can i send it to you via e-mail?
I added my input field,but saving values don’t work, i don’t have any errors, just no results in order pages
Laura
Really just struggling with how to set this up for an array of products instead of just one. Or even an array of categories would be nice. Help??
Laura
Also having trouble getting the jquery part to work right. I’ve inserted it into the of my header.php file like this:
jQuery(‘.name-checkbox input[type=”checkbox”]’).on(‘click’, function () {
jQuery(‘.name-text’).slideToggle();
jQuery(‘.name-text’).slideToggle();
});
alert(‘Custom jquery Code has been executed’);
});
I first tried the “jQuery” as “$” and that didn’t work either. Should I be putting this somewhere else? Thanks in advance.
Devin Walker
You need to wrap the code in a document ready statement so it can execute properly.
Like so:
jQuery(document).ready(function(){
//My code goes here
});
Laura
So, like this?
jQuery(document).ready(function(){
$(‘.name-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.name-text’).slideToggle();
$(‘.name-text’).slideToggle();
});
alert(‘Custom jquery Code has been executed’);
});
});
But that’s not working either 🙁
Devin Walker
You have an extra closing statement “});” at the end…
Laura
Ahhhhh! Thank you. It’s now working GREAT! Now if I could just figure out how to have this work for an array of products instead of just 1, my task would be complete!
Mark
Hi,
Could this be adapted so that the customer could pick a number from a drop down (e.g. 1-10), which would then create that number of empty fields for the customer to fill in? I am trying to this for a website that does group bookings and needs the customer to fill in the names, ages, and other details of each attendee.
Any help would be much appreciated.
Cheers
Devin Walker
Yes it definitely could be, but would require some significant changes to the code. A decent enough WordPress developer could get that done in a few hours.
Mark
Thanks for the quick reply. Any idea where I could source someone and a rough estimate of cost?
Devin Walker
Freelance.com or a WordPress specific development shop would be glad to take it on… average developer costs anywhere from $50 – $200 / hr.
Santukon
Hello Devin and rest of the people!!
I´m trying to go little bit further, I hope you or someone can help me. The thing is, I´m trying to use this code to have custom field on woocommerce bookings, depending on the quantity of people, At the moment, it almost works, it is multipliying de fields, but, I can not make it to be saved on the order and sent by email.
The code I´m using is the following:
/**
* Add the field to the checkout
**/
add_action( ‘woocommerce_after_order_notes’, ‘wordimpress_custom_checkout_field’ );
function wordimpress_custom_checkout_field( $checkout ) {
//Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID)
$book_in_cart = wordimpress_is_conditional_product_in_cart( 74 );
//Check to see if user has product in cart
global $woocommerce;
//Book is in cart so show additional fields
if ( $book_in_cart === true ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key ) {
global $adultos;
$adultos = $cart_item_key[‘booking’][‘_persons’][‘160’];
for ($i=1; $i <= $adultos; $i++) {
echo ' ‘;
if($i==1){echo ‘CanyoningInformación requerida por persona para realizar la actividad de Canyoning’;}
echo ‘Adulto: ‘.$i.”;
woocommerce_form_field(‘nombre_textbox_adulto’.$i, array(
‘type’ => ‘text’,
‘class’ => array( ‘nombre_textbox’ ),
‘label’ => __( ‘Nombre y apellido’ ),
‘required’ => true
), $checkout->get_value(‘nombre_textbox_adulto’.$i) );
echo ”;
}
}
}
}
/**
* Check if Conditional Product is In cart
*
* @param $product_id
*
* @return bool
*/
function wordimpress_is_conditional_product_in_cart( $product_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag no book in cart
$book_in_cart = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values[‘data’];
if ( $_product->id === $product_id ) {
//book is in cart!
$book_in_cart = true;
}
}
return $book_in_cart;
}
/**
* Update the order meta with field value
**/
add_action( ‘woocommerce_checkout_update_order_meta’, ‘wordimpress_custom_checkout_field_update_order_meta’ );
function wordimpress_custom_checkout_field_update_order_meta( $order_id ) {
//check if $_POST has our custom fields
global $adultos;
for ($i=1; $i <=$adultos; $i++) {
if ( $_POST['nombre_textbox_adulto'.$i] ) {
update_post_meta( $order_id, 'Nombre y apellido', esc_attr( $_POST['nombre_textbox_adulto'.$i] ) );
}
}
}
/**
* Add the field to order emails
**/
add_filter( 'woocommerce_email_order_meta_keys', 'wordimpress_checkout_field_order_meta_keys' );
function wordimpress_checkout_field_order_meta_keys( $keys ) {
//Check if Book in Cart
$book_in_cart = wordimpress_is_conditional_product_in_cart( 74 );
//Only if book in cart
if ( $book_in_cart === true ) {
global $adultos;
for ($i=1; $i <=$adultos; $i++) {
$keys[] = 'nombre_textbox_adulto'.$i;
}
}
return $keys;
}
Woogz
Hi Santukon!
I am looking for this exact functionality and wondering if you ever got it to work?
Thanks 🙂
dzulfriday
Is it possible to have different checkout fields for different product? For example, i want customers to upload their scanned ID for this one particular product. Not all product.
Devin Walker
It certainly is… you would simply need to query the user’s cart items first to see if a specific product is added and then write a conditional check to verify that before any fields are added.
dzulfriday
How to do that?
Tuan Vo
Hi, Billing Address now
displaying First Name – Last Name. Do you know how to re-order it display Last Name –
First Name http://i.imgur.com/Jg5xFmM.jpg
Santukon
got it working
Pamela Carpenter
How can the form be validated. For example – if inscription-text=1 (is checked) and inscription-textbox is visible, don’t accept the form without the text in the box.
Pamela Carpenter
For anyone trying to do this, here is how to add the error if there’s no text in the box:
/**
* Process the checkout
*/
add_action(‘woocommerce_checkout_process’, ‘pam_custom_checkout_field_process’);
function pam_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if( $_POST[‘inscription_checkbox’])
{
if(($_POST[“inscription_textbox”] == “Please enter expiration date *”) || ($_POST[“inscription_textbox”] == “”))
//if($_POST[“inscription_textbox”] != “Pam”)
{
wc_add_notice( __( ‘Please enter expiration date *’ ), ‘error’ );
}
}
else
{
}
}
cecilywiggins
How about using conditional fields to confirm the shipping address. Is this possible?
Jason
I’m also having difficulty getting the JQuery to work. I have enqueued the script into the head. I can see the script is loaded on the page but it not working. The js file I created:
jQuery(document).ready(function(){
$(‘.inscription-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.inscription-text’).slideToggle();
});
});
Alan Cordova
maybe is because you are using $ instead jQuery try this:
jQuery(document).ready(function(){
jQuery(‘.inscription-checkbox input[type=”checkbox”]’).on(‘click’, function () {
jQuery(‘.inscription-text’).slideToggle();
});
});
or try with this
jQuery.noConflict();
(function( $ ) {
$(function() {
$(‘.inscription-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.inscription-text’).slideToggle();
});
});
})(jQuery);
sorry for the indexing, i dont know how put here xD
Marcio
I created a dropdown question (Do you have insurance?) to our checkout page. I am trying to do some conditional logic like, but not related to a product, just about this first question.
Like:
add_action( ‘woocommerce_before_checkout_form’, ‘question_insurance’ );
function question_insurance( $checkout ) {
echo ” . __(‘Do you have Insurance?’) . ”;
woocommerce_form_field ( ‘question_insurance’, array(
‘type’ => ‘select’,
‘class’ => array(‘question-insurance-class form-row-wide’),
‘label’ => __(‘Do you have insurance?’),
‘placeholder’ => __(‘none’, ‘woocommerce’),
‘options’ => array(
‘option_a’ => __(‘No’, ‘no’ ),
‘option_b’ => __( ‘Yes’,’yes’ ),
),
‘required’ => true,
), $checkout->get_value( ‘question_insurance’ ));
echo ”;
}
add_action( ‘woocommerce_before_checkout_form’, ‘insurance_yes’ );
function insurance_yes( $checkout ) {
if (option_b) === true {
echo ” . __(‘its working’) . ”;
# code…
echo ”;
}
Any thoughts, tips, recommendations or responses WILL BE APPRECIATED !
Thank you!
Nacho Arribas
Hello. I put the code ok for one product, but now i want to put another conditional checkout fields for anothe product. I dont´t how to do it.
Giovanni
hi, i ask where to insert the code
$(‘.inscription-checkbox input[type=”checkbox”]’).on(‘click’, function () {
$(‘.inscription-text’).slideToggle();
});
???
Shaun
Works awesome but any idea when I try to add the post meta data and email data it returns …. Array and then has the shows the data??
Thanks!
Aaron Dickey
This works perfectly. Is there a function to allow the custom field data to show up on the WooThemes Print Invoices plugin?
https://woocommerce.com/products/print-invoices-packing-lists/
alxndrdvl
Hey, thank you for this, exactly what I was looking for !
What would be the proper syntax to add a select field instead?
Tried this :
woocommerce_form_field( ‘my-gender’, array(
‘type’ => ‘select’,
‘class’ => array( ‘Male’ => ‘Male’, ‘Female’ => ‘Female’ ),
‘label’ => __( ‘Gender’ ),
), $checkout->get_value( ‘my-gender’ ) );
But it doesn’t work 🙁 No error message, just doesn’t show up…
Thank you !
alxndrdvl
Nevermind, I found a way to make it work! Also added a line if info is required.
Thought I would share it :
woocommerce_form_field( ‘my-gender-select’, array(
‘placeholder’ => _x(”, ‘placeholder’, ‘woocommerce’),
‘required’ => true,
‘type’ => ‘select’,
‘options’ => array(
‘male’ => __(‘Male’, ‘Male’ ),
‘female’ => __(‘Female’, ‘Female’ )
),
‘class’ => array( ‘my-gender-select form-row-wide’ ),
‘label’ => __( ‘Gender’ ),
), $checkout->get_value( ‘my-gender-select’ ) );
woocommerce_form_field( ‘inches-or-cm’, array(
‘placeholder’ => _x(”, ‘placeholder’, ‘woocommerce’),
‘required’ => true,
‘type’ => ‘select’,
‘options’ => array(
‘inches’ => __(‘in’, ‘in’ ),
‘centimeters’ => __(‘cm’, ‘cm’ )
),
‘class’ => array( ‘my-measurement-unit-select form-row-wide’ ),
‘label’ => __( ‘Measurement Unit’ ),
), $checkout->get_value( ‘inches-or-cm’ ) );
Muneeb Ziaa
hi #alxndrdvl
Hope you are fine. did you add any anything else other then required? because I have added it but it is not working, the checkout is still processing without any values added in the fields?
Hoping to hear form you soon. thanks
Schalk
Hi,
How can I display, in order emails:
Inscription Option: Yes
instead of
Inscription Option: 1
Paulo Vaz
What about a custom field based on some shippment methods?
Sontod
Thanks Devin, this does exactly what I need!
Max
I’m struggling with this problem:
– When a coupon is applied I need to show the order comments as a required field.
– When no coupon is used I want to hide the order comments.
The snippet to unset the order_comments is easy to find but when I try that it’s still a required field, so impossible to check out. I assumed hiding meant that the required setting became obsolete automatically.
Is there a way to unset order_comments and make it optional at the same time?
Any pointers for this scenarion?
Muneeb Ziaa
Bro you are awsome and this code worked like a charm. Just one question, how can I make the feilds require/compulsary
Agus Halim
Hi, Thanks for the code. i try to implement to my site. but always return error. may i check if all this code put into functions.php in woocommerce ? my woocommerce version is 2.6.8 thanks in advance
Matt Boden
The code should go in the functions.php file that sits within your child theme, not woocommerce.
Tirth
Hello all,
Nicely presented !
This plugin may solve the problem easy, it allows you to charge extra fees in cart, based on the combination of multiple conditional rules that you configure in your woocommerce store.
I hope it may help!
WooCommerce Conditional Product Fees For Checkout
Nicholas M
How has nobody taken this code and turned it into a plugin yet?
Uriahs Victor
Lol they have, there are a few conditional field plugins out there.
Welmoed Verhagen
Hi! Thank you for this information! Could something like this be used to add a “Would you like to provide a signature upon receiving your package – cost $5” to a shopping cart in WooCommerce? It would need to add the $5 to the total amount the person is purchasing. Thank you!
Kristy Stevens
Do you have information on how to change the code to test for category of products instead of single products? Sorry if its simple PHP newbie.
Sajid
I am selling event tickets. I want to collect the event attendees details (Name, Email, Phone) as well. Using WooCommerce, selling the tickets is easy. The problem is, the during checkout, the payment gateway just request for the buyer details only.
This is fine if the buyer buys 1 ticket only. The problem is when buyer buys more than 1 ticket. For example, when buyer buys 3 tickets, I want before payment is done, I can collect the attendees name, email and phone based on the quantity of the tickets they choose.
Mikel
The provided jQuery did not work for me.
What worked for me is:
jQuery(document).ready(function($) {
$(‘.inscription-checkbox’).click(function() {jQuery(‘.inscription-text’).slideToggle();
});
});