Unable to save custom checkbox value from WooCommerce checkout

Viewed 359

I created function that adds checkbox to the WooCommerce checkout after billing form.

Checkbox appears, everything looks OK on the front end.

add_filter( 'woocommerce_after_checkout_billing_form' , 'add_field_sendy_woocommerce_agree', 9);

function add_field_sendy_woocommerce_agree( ) {

    woocommerce_form_field( 'sendy_woocommerce_agree', array(
    'type'          => 'checkbox',
    'label'         => __('Subscribe to our Newsletter.'),
    'required'  => false,
    'default' => 1 
    ),  WC()->checkout->get_value( 'sendy_woocommerce_agree' ));                               
}

The problem is that checkbox is not saved as metadata. In the wp_postmeta table, _sendy_woocommerce_agree meta key is missing after submission.

So I can not access it with $xyz = $order->get_meta( '_sendy_woocommerce_agree' );

What am I doing wrong?

1 Answers

Give it a try in the following way

function add_field_sendy_woocommerce_agree( $checkout ) {

    woocommerce_form_field( 'sendy_woocommerce_agree', array(
        'type'          => 'checkbox',
        'label'         => __('Subscribe to our Newsletter.'),
        'required'  => false,
        'default' => 1 
    ),  $checkout->get_value( 'sendy_woocommerce_agree' ));                               
}
add_filter( 'woocommerce_after_checkout_billing_form' , 'add_field_sendy_woocommerce_agree', 10, 1 );

// Save
function action_woocommerce_checkout_create_order( $order, $data ) {
    if ( isset($_POST['sendy_woocommerce_agree']) && ! empty($_POST['sendy_woocommerce_agree']) ) {
        $order->update_meta_data( 'sendy_woocommerce_agree', sanitize_text_field( $_POST['sendy_woocommerce_agree'] ) );
    } 
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );

// Display the custom field value on admin order pages after billing adress:
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
    echo '<p><strong>'.__('Sendy').':</strong> ' . $order->get_meta('sendy_woocommerce_agree') . '</p>'; 
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
Related