questions

Add a checkbox that show / hide order notes on WooCommerce Checkout

Rate this post

I am trying to add a checkbox that shows or hides the original “additional notes” from WooCommerce. Does anyone have any idea how to do so?

I will use Add a checkbox to show / hide checkout fields in Woocommerce answer code, to add that checkbox in checkout page.

The original “additional notes” from woocommerce is under form-shipping.php and it goes like this:

<div class="woocommerce-additional-fields">
    <?php do_action( 'woocommerce_before_order_notes', $checkout ); ?>

    <?php if ( apply_filters( 'woocommerce_enable_order_notes_field', 'yes' === get_option( 'woocommerce_enable_order_comments', 'yes' ) ) ) : ?>

        <?php if ( ! WC()->cart->needs_shipping() || wc_ship_to_billing_address_only() ) : ?>

            <h3><?php esc_html_e( 'Additional information', 'woocommerce' ); ?></h3>

        <?php endif; ?>

        <div class="woocommerce-additional-fields__field-wrapper">
            <?php foreach ( $checkout->get_checkout_fields( 'order' ) as $key => $field ) : ?>
                <?php woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); ?>
            <?php endforeach; ?>
        </div>

    <?php endif; ?>

    <?php do_action( 'woocommerce_after_order_notes', $checkout ); ?>
</div>

 

✔️Solution:

The following will add a checkbox that will show / hide Woocommerce default order notes on checkout page:

add_filter( 'woocommerce_checkout_fields', 'custom_checkout_order_notes' );
function custom_checkout_order_notes( $fields ) {
    $fields['order']['order_comments']['class'][] = 'off';
    return $fields;
}

add_action( 'woocommerce_before_order_notes', 'checkout_checkbox_show_hide_order_notes' );
function checkout_checkbox_show_hide_order_notes( $fields ) {
    $target_id = 'order_comments';
    ?>
    <style> p#<?php echo $target_id; ?>_field.off { display:none;}</style>
    <script type="text/javascript">
    jQuery(function($){
        var a = 'input#checkbox_trigger',       b = '#<?php echo $target_id; ?>_field';

        $(b).hide('fast');

        $(a).change(function(){
            if( $(b).hasClass('off') ) {
                $(b).removeClass('off');
            }

            if ( $(this).prop('checked') ) {
               $(b).show('fast');
            } else {
                $(b).hide('fast', function(){
                    $(b+' input').val('');
                });
            }
        });
    });
    </script>
    <?php

    woocommerce_form_field( 'checkbox_trigger', array(
        'type'      => 'checkbox',
        'label'     => __('Add a note to your order?', 'woocommerce'),
        'class'     => array('form-row-wide'),
        'clear'     => true,
    ), false );
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Leave a Reply

Your email address will not be published.

Back to top button