I added a custom field to the checkout (select field) and I would like to save that field along with all the other fields, but it is not showing me the custom field at all on any plugin I am using.
This is the code I added to my functions.php file:
//* Add select field to the checkout page
add_action('woocommerce_before_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
woocommerce_form_field( 'studio', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Select your studio' ),
'required' => true,
'priority' => 5, // Priority sorting option
'options' => array(
'blank' => __( 'Select Your Studio', 'wps' ),
'Ukraine & Poland' => __('Ukraine & Poland', 'wps' ),
'Israel' => __('Israel', 'wps' ),
'Kyiv' => __('Kyiv', 'wps' ),
'Finland ' => __('Finland', 'wps' )
)
),
$checkout->get_value( 'studio' ));
}
//* Process the checkout
add_action('woocommerce_checkout_process', 'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error.
if ($_POST['studio'] == "blank")
wc_add_notice( '<strong>Please select your studio</strong>', 'error' );
}
Any idea what I need to do in order to save this field?
2
Answers
Your code is ok but you dont save the field!
Add this to save the field in order meta data:
Then you can retrieve it as any other meta field. Here is a function that will output the selection made in field ‘studio’:
Usage:
Note: I strongly recommend to not use "studio" for the field name, add a preffix to avoid conflicts i.e. "wps_studio"
You need to save your custom checkout field selected value as order metadata like:
Since version 3, WooCommerce is migrating to custom database tables, (specially for orders), and with recent High Performance Order Storage (HPOS), the only way is to use setter methods to save the custom metadata, instead of using WordPress post meta functions.
For example you can display it in admin orders with:
So as you see, you can access ‘studio’ metadata from the
WC_Order
object like:This is compatible with legacy Post data and High Performance Order Storage (HPOS).