With WooCommerce, I have some issue saving value from a custom field into the database. I have followed several guides, but for some reason it doesn't work for me.
Here is the code I'm adding to my function PHP-file:
// Print out checkbox on checkout
add_shortcode( 'replacement_item', 'custom_woocommerce_form_shortcode' );
function custom_woocommerce_form_shortcode() {
ob_start(); // Start output buffering
// Output the form field using woocommerce_form_field function
woocommerce_form_field( 'replacement_checkbox', array(
'type' => 'checkbox',
'default' => true,
'class' => array('input-checkbox'),
'label' => __('Allow substitute items for all products.'),
), WC()->checkout->get_value( 'replacement_checkbox' ) );
// Get the buffered content and return it
$output = ob_get_clean();
return $output;
}
// save value from checkbox above to database --
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta', 10, 1 );
function custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['replacement_checkbox'] ) )
update_post_meta( $order_id, 'replacement_checkbox', $_POST['replacement_checkbox'] );
}
Note that'm using Block checkout and the checkbox field is displayed as follows:
