You can save custom field data in WooCommerce as order meta key by using the following code:
add_action( 'woocommerce_after_order_notes', 'add_custom_checkout_field' );
function add_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Enter Something'),
'placeholder' => __('Enter Something'),
'required' => false,
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
This will add a custom field named "myfieldname" to the checkout page.
add_action( 'woocommerce_checkout_update_order_meta', 'save_my_field_name' );
function save_my_field_name( $order_id ) {
if ( ! empty( $_POST['my_field_name'] ) ) {
update_post_meta( $order_id, 'My Field Name', sanitize_text_field( $_POST['my_field_name'] ) );
}
}
This code will save the value of the "myfieldname" custom field as an order meta key named "My Field Name". You can replace "My Field Name" with whatever meta key name you'd like to use.
That's it! Now, the custom field data will be saved as an order meta key in WooCommerce.
Asked: 2022-03-22 11:00:00 +0000
Seen: 11 times
Last updated: Aug 29 '22