Rohitashv Singhal
Rohitashv Singhal

Reputation: 4557

Unable to add custom select field in woocommerce

I want to add a custom field options to checkout page. I am using the following code :

$fields['billing']['billing_options'] = array(
    'label'       => __('Options', 'woocommerce'),
    'placeholder' => _x('', 'placeholder', 'woocommerce'),
    'required'    => false,
    'clear'       => false,
    'type'        => 'select',
    'options'     => array(
        'option_a' => __('option a', 'woocommerce' ),
        'option_b' => __('option b', 'woocommerce' )
        )
    );

I want to show the options (option_a,option_b) from database or I want to use dynamic data and want to use for loop in the options menu

How can I use for loop inside this function ?

Upvotes: 1

Views: 95

Answers (1)

Pelmered
Pelmered

Reputation: 2882

Just do it before, like this:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function my_custom_checkout_fields( $fields ) {

    $args = array(                                                                  
        'post_type'         => array('options'),                                    
        'posts_per_page'    => -1                                                           
    );                                                                              

    $posts = new WP_Query($args);
    $options = array();        

    foreach ($posts as $post) {  
        $options[$post->ID] => attr_esc($post->post_title);
    }

    $fields['billing']['billing_options'] = array(
        'label'       => __('Options', 'woocommerce'),
        'placeholder' => _x('', 'placeholder', 'woocommerce'),
        'required'    => false,
        'clear'       => false,
        'type'        => 'select',
        'options'     => $options
    );
    return $fields;
}

Upvotes: 2

Related Questions