rachael-portier
1/8/2020 - 6:02 PM

Add Custom Field to Checkout (Dropdown)

https://jeroensormani.com/ultimate-guide-to-woocommerce-checkout-fields/

  1. Create Field
  2. Add Field Input to Admin Order in Customer Info
// 1. CREATE FIELD WITH FIELD TYPE, OPTIONS, AND PLACEMENT
function location_type_field( $fields ) {
   $fields['billing_location_type'] = array(
        'label'        => __( 'type of location' ),
        'type'        => 'select',
        'class'        => array( 'location-type form-row-wide' ),
        'priority'     => 95,
        'required'     => true,
	   'options'     => array(
	                    '' => __('Location Type'),
                      'Com' => __('Commercial'),
                      'Res' => __('Residential')
    	),
    	'default' => '');

    return $fields;
}
add_filter( 'woocommerce_billing_fields', 'location_type_field' );


// 2. SAVE FIELD TO SPECIFIC ORDER
function save_extra_checkout_fields( $order_id, $posted ){
    // don't forget appropriate sanitization if you are using a different field type
   
    if( isset( $posted['billing_location_type'] ) && in_array( $posted['billing_location_type'], array( 'Commercial', 'Residential' ) ) ) {
        update_post_meta( $order_id, '_billing_location_type', $posted['billing_location_type'] );
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'save_extra_checkout_fields', 10, 2 );


// 3. ADD CUSTOM FIELD TO CUSTOMER INFO IN ORDER
function add_location_type_field_to_admin_order( $fields ) {
    $fields['location_type'] = array(
        'label' => __( 'Location Type' ),
        'show' => true,
    );

    return $fields;
}
add_filter( 'woocommerce_admin_billing_fields', 'add_location_type_field_to_admin_order' );



// 4. PRINT CUSTOM FIELD
<?php echo $order->get_meta( '_billing_location_type', true ); ?>