I am trying to add a dropdown field at checkout which needs to be validated before order submission and stored in the order for admin to view in order details. But for some reason even after i select the dropdown option, it says a value must be selected for the field.
add_filter( 'woocommerce_after_checkout_form', 'custom_checkout_fields' );
function custom_checkout_fields( $checkout ) {
// The selector
woocommerce_form_field( 'allow_substitute', array(
'type' => 'select',
'required' => true,
'class' => array('my-field-class form-row-wide'),
'label' => __('Allow Product substitution when a cigar is out of stock?', 'my_theme_slug'),
'options' => array(
'' => __('Choose an option', 'my_theme_slug'),
'option1' => 'Allow product substitution (When a cigar is out of stock, a similar cigar will be shipped.',
'option2' => 'Call me before making a product substitution',
'option3' => 'Refund the cigar order value that is out of stock'
)
), $checkout->get_value( 'allow_substitute' ));
echo '</div>';
}
// Process the checkout
add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
function custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['allow_substitute'] ) // the selector
wc_add_notice( __( 'Please select a value for "Product Substitution?" field.' ), 'error' );
}
// Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta' );
function custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['allow_substitute'] ) ) {
update_post_meta( $order_id, 'allow_substitute', sanitize_text_field( $_POST['allow_substitute'] ) );
}
}