简体   繁体   中英

Woocommerce add a checkbox in checkout page

I need to add programatically a checkbox in my checkout page, but not a checkbox like "accept term and conditions". It would be a checkbox with a value (calculated) and this value would be added to the total order price if checked.

I need also to get this value in order history and emails. I have this code but in this case nothing is added to the total if the checkbox is checked.

/**
 * 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']));
    }

I use part of this code and changed $woocommerce->add_error( __('Please agree to my checkbox.') ); Its working. maybe some problems with WC2.x -> 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.') );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM