2

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?

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
Mike
  • 117
  • 1
  • 4
  • 12
  • @LoicTheAztec Sorry for the duplicate, honestly I did not find the other answer with the search terms relevant to me here on website nor with Google, the answer is indeed what I was looking for but the question is a questionable duplicate :) – Mike May 16 '20 at 14:19
  • No problem don't worry, sometimes it's difficult to find out an existing related answer… The answer here below is just fine, as a bit different. – LoicTheAztec May 16 '20 at 15:07

1 Answers1

1

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 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50