Woocommerce在结帐页面添加一个复选框

时间:2017-06-02 08:08:45

标签: php woocommerce

我需要在我的结帐页面中以编程方式添加一个复选框,但不是像"接受条款和条件"这样的复选框。它将是一个带有值(已计算)的复选框,如果选中此值,则该值将添加到总订单价格中。

我还需要在历史记录和电子邮件中获取此值。 我有这个代码,但在这种情况下,如果选中复选框,则不会向总计中添加任何内容。

/**
 * Add checkbox field to the checkout
 **/
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');

function my_custom_checkout_field( $checkout ) {

    echo '<div id="my-new-field"><h3>'.__('My Checkbox: ').'</h3>';

    woocommerce_form_field( 'my_checkbox', array(
        'type'          => 'checkbox',
        'class'         => array('input-checkbox'),
        'label'         => __('I have read and agreed.'),
        'required'  => true,
        ), $checkout->get_value( 'my_checkbox' ));

    echo '</div>';
}


    /**
     * Process the checkout
     **/
    add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

    function my_custom_checkout_field_process() {
        global $woocommerce;

        // Check if set, if its not set add an error.
        if (!$_POST['my_checkbox'])
             $woocommerce->add_error( __('Please agree to my checkbox.') );
    }

    /**
     * Update the order meta with field value
     **/
    add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');

    function my_custom_checkout_field_update_order_meta( $order_id ) {
        if ($_POST['my_checkbox']) update_post_meta( $order_id, 'My Checkbox', esc_attr($_POST['my_checkbox']));
    }

1 个答案:

答案 0 :(得分:0)

我使用了此代码的一部分并更改了$woocommerce->add_error( __('Please agree to my checkbox.') );它的工作原理。也许是WC2.x的一些问题 - &gt; WC3.0

function my_custom_checkout_field_process() {
    global $woocommerce;

    // Check if set, if its not set add an error.
    if (!$_POST['my_checkbox'])
        wc_add_notice( __('Please agree to my checkbox.') );
}