Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce conditional fields for gifts options on checkout
<?php
##############################
/*
Conditionally show gift add-ons if user checks a box saying they would like to send the order as a gift.
Created by craig@123marbella.com on 13th of July 2017
As default, WooCommerce simply displays ALL the add ons so makes the checkout form look very long.
This is useful if you want to show a checkbox on your checkout saying "Is this a gift order?"
and when the user checks the box, a list of all the options will be available to the user.
NOTE: you need to have the WooCommerce Checkout Add-Ons installed.
Inside Woocommerce do the following:
1. Open WooCommerce > Check Out Add ons
2. Create an addon called "Is this a gift order?"
3. Make it checkbox
4. Make Options / Costs field value as 0
5. Add your various add ons
Then add the following code to your functions.php file.
Show and hide the other field by changing the numeric id part of the add on field name.
EG: wc_checkout_add_ons_XXX_field <--- would become: wc_checkout_add_ons_3_field
*/
##############################
function wc_checkout_add_ons_conditionally_show_gift_add_on() {
wc_enqueue_js( "
$( 'input[name=wc_checkout_add_ons_6]' ).change( function () {
if ( $( this ).is( ':checked' ) ) {
// show the gift checkout add-on -- replace '3,5,8,2' with the id of your add-ons
$( '#wc_checkout_add_ons_3_field' ).show();
$( '#wc_checkout_add_ons_5_field' ).show();
$( '#wc_checkout_add_ons_8_field' ).show();
$( '#wc_checkout_add_ons_2_field' ).show();
} else {
// hide the gift checkout add-on -- replace '3,5,8,2' with the id of your add-ons
$( '#wc_checkout_add_ons_3_field' ).hide();
$( '#wc_checkout_add_ons_5_field' ).hide();
$( '#wc_checkout_add_ons_8_field' ).hide();
$( '#wc_checkout_add_ons_2_field' ).hide();
}
} ).change();
" );
}
add_action( 'wp_enqueue_scripts', 'wc_checkout_add_ons_conditionally_show_gift_add_on' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.