在 WooCommerce Checkout 上添加一个显示/隐藏订单备注的复选框

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

我正在尝试添加一个复选框来显示或隐藏来自 WooCommerce 的原始“附加说明”。有人知道怎么做吗?

我将使用 答案代码,在结帐页面中添加该复选框。

woocommerce 的原始“补充说明”在 form-shipping.php 下,它是这样的:

<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>

以下将添加一个复选框,该复选框将在结帐页面上显示/隐藏 Woocommerce 默认订单备注:

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 );
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。