Support » Plugins » How to get the text value from select options in woocommerce

  • Hi,

    I was hoping if anyone could help me out with my question. I’ve just added a new custom field (select options) to my woocommerce_checkout fields as follows:

    add_filter('woocommerce_checkout_fields','custom_override_checkout_fields');
    function custom_override_checkout_fields($fields) {
       $fields['billing']['billing_reasonpurchase'] = array(
           'label' => __('Reason for purchase', 'woocommerce'),
           'placeholder' => _x('Reason for purchase', 'placeholder', 'woocommerce'),
           'required' => false,
           'type' => 'select',
           'class' => array('form-row-first'),
           'options' => array(
               'option_1' => __('Personal', 'woocommerce'),
               'option_2' => __('Academic', 'woocommerce'),
               'option_3' => __('Small Business', 'woocommerce'),
               'option_4' => __('Large Organization', 'woocommerce')
           )
       );
       return $fields;
    }

    This works so far, and then because I want to save this new field to order custom fields, I don’t know how to go about this. I use the example given in http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/

    add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
    
    function my_custom_checkout_field_update_order_meta( $order_id ) {
        if ( ! empty( $_POST['billing_reasonpurchase'] ) ) {
            update_post_meta( $order_id, 'Reason for purchase', sanitize_text_field( $_POST['billing_reasonpurchase'] ) );
        }
    }

    Then, followed by:

    add_action('woocommerce_admin_order_data_after_billing_address','my_custom_checkout_field_display_admin_order_meta',10,1);
    function my_custom_checkout_field_display_admin_order_meta($order){
       echo '<p><strong>'.__('Reason for purchase').':<strong>'.get_post_meta($order->id, 'Reason for purchase',true).'</p>';
    }

    but unfortunately, the code is for a simple text field. When I put the code inside my theme functions.php, I got the option_id rather than the “text”. For example, if I selected option_2 for Academic, it gives me “option_2” rather than “Academic” in the order details.

    How would I go about this so that the result I’d get is the actual text rather than the option id.

    Thank you in advance

  • The topic ‘How to get the text value from select options in woocommerce’ is closed to new replies.