[wd_asp elements=’search’ ratio=’100%’ id=1]

Add a dropdown to Woocommerce Checkout Fields

20th January 2021

WooCommerce

woocommerce category codehaven

To add a dropdown or select element to the fields on a woocommerce checkout, this can be achieved by the following code.

Just add this code and amend where necessary to the functions.php file.

Add dropdown

// where found us
//* 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 ) {

echo '

';

woocommerce_form_field( 'myquestion', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'How did you find out about us?' ),
'options' => array(
'blank' => __( 'Please Select', 'wps' ),
'google' => __( 'Search engine (Google etc)', 'wps' ),
'brochure' => __( 'Brochure', 'wps' ),
'recommedation' => __( 'Recommendation', 'wps' )
)
),

$checkout->get_value( 'myquestion' ));

}

Update dropdown


//* Update the order meta with field value
add_action('woocommerce_checkout_update_order_meta', 'wps_select_checkout_field_update_order_meta');
function wps_select_checkout_field_update_order_meta( $order_id ) {

if ($_POST['myquestion']) update_post_meta( $order_id, 'myquestion', esc_attr($_POST['myquestion']));

}

Display dropdown answer


//* Display field value on the order edition page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wps_select_checkout_field_display_admin_order_meta', 10, 1 );
function wps_select_checkout_field_display_admin_order_meta($order){

echo '

'.__('Found by').': ' . get_post_meta( $order->id, 'myquestion', true ) . '

';

}

//* Add selection field value to emails
add_filter('woocommerce_email_order_meta_keys', 'wps_select_order_meta_keys');
function wps_select_order_meta_keys( $keys ) {

$keys['myquestion:'] = 'myquestion';
return $keys;

}