在 Woocommerce 的条款和条件下方添加自定义结帐字段

Add custom checkout fields below the terms and conditions in Woocommerce

我使用 Woocommerce 建立了一个电子商务网站。我想在条款和条件下方再添加两个复选框。我到处都在寻找一个可行的解决方案,但我唯一找到的是一个商业插件。

如何以编程方式在条款和条件下方添加自定义结帐字段(2 个复选框)?

条款和条件屏幕截图的位置:

  • 第一个挂钩函数显示 2 个附加结帐字段
  • 第二个挂钩函数将检查两个复选框是否"selected"以允许结帐,如果不是则显示自定义错误通知...

代码:

add_action('woocommerce_checkout_before_terms_and_conditions', 'checkout_additional_checkboxes');
function checkout_additional_checkboxes( ){
    $checkbox1_text = __( "My first checkbox text", "woocommerce" );
    $checkbox2_text = __( "My Second checkbox text", "woocommerce" );
    ?>
    <p class="form-row custom-checkboxes">
        <label class="woocommerce-form__label checkbox custom-one">
            <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_one" > <span><?php echo  $checkbox1_text; ?></span> <span class="required">*</span>
        </label>
        <label class="woocommerce-form__label checkbox custom-two">
            <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_two" > <span><?php echo  $checkbox2_text; ?></span> <span class="required">*</span>
        </label>
    </p>
    <?php
}

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['custom_one'] )
        wc_add_notice( __( 'You must accept "My first checkbox".' ), 'error' );
    if ( ! $_POST['custom_two'] )
        wc_add_notice( __( 'You must accept "My second checkbox".' ), 'error' );
}

代码进入您的活动子主题(活动主题)的 function.php 文件。

已测试并有效。