[SOLVED] WooCommerce conditional fields for gifts options on checkout

July 20, 2017

Built a web site recently using WooCommerce and decided that a gift wrapping option would be wonderful idea when user checks out.

However, the WooCommerce Checkout Add-Ons plugin whilst its great, is still in its infancy and on the checkout page, it simply populates the page with all the add ons, so makes the checkout page look HUGE!

My idea, was to add a checkbox asking the user if they wanted to gift wrap the order and then when checked, a list of the options would appear.

##############################
/*
Conditionally show gift add-ons if user checks a box saying they would like to send the order as a gift.

Created by craig@craigedmonds.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' );