samedi 26 décembre 2020

How to save from WooCommerce checkout a custom checkbox field state?

I have a problem with the update_post_meta function. I have a user submitted value, which I pass via $_POST and then saving to post meta.

All is working fine, but when the value is '0' the post meta is not updated.

This is My code:

// Add custom checkout field: woocommerce_review_order_before_submit
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field_ritiro_sede' );
function my_custom_checkout_field_ritiro_sede() {
    echo '<div class="cw_custom_class"><h3>'.__('Ritiro presso sede CER S.r.l. &nbsp').'</h3>';
    echo '<div id="my_custom_checkout_field">';
    woocommerce_form_field( 'ritiro_sede', array(
        'type'      => 'checkbox',
        'class'     => array('input-checkbox'),
        'label'     => __('SI'),
    ),  WC()->checkout->get_value( 'ritiro_sede' ) );
    echo '</div>';
}

// Save the custom checkout field in the order meta, when checkbox has been checked
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta_ritiro_sede', 10, 1 );
function custom_checkout_field_update_order_meta_ritiro_sede( $order_id ) {

    if ( ! empty( $_POST['ritiro_sede'] ) )
        update_post_meta( $order_id, 'ritiro_sede', $_POST['ritiro_sede'] );
    if ( isset( $_POST['ritiro_sede'] ) )
        update_post_meta( $order_id, 'ritiro_sede', $_POST['0'] );
    
}

Does anyone have any idea what might be wrong?




Aucun commentaire:

Enregistrer un commentaire