• Hi, I’m trying to add a custom select field to the checkout page and I’m using the function woocommerce_form_field to add one.

    I’m trying to pass an array to the options so that I don’t have to manually write all the possible options.

    Here is the code I currently have (which doesn’t work).

    woocommerce_form_field( 'store_selection', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Fill in this field'),
            'placeholder'   => __('Enter something'),
            'options'		=> array($stores['value'] => $stores['option']),
            ), $checkout->get_value( 'store_selection' ));

    It’s this part that I don’t get how to use properly:
    ‘options’ => array($stores[‘value’] => $stores[‘option’]),

    Can anyone help with this issue?

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter cocosay

    (@cocosay)

    EDIT:

    This is how I fill in my array

    while ( $loop->have_posts() ) : $loop->the_post();
    		$title = get_the_title();
    		$email = get_field( 'email', get_the_ID() );
    		$postType = get_post_type();
    		$obj = get_post_type_object( $postType );
    		$singularName = $obj->labels->singular_name;
    		$option = $singularName . ' - ' . $title;
    
    		array_push( $stores, array('value' => $email, 'option' => $option) );
    		
    		//array_push($values, $email);
    	endwhile;

    I’ve tried to use one array for the values and one for the options first but it didn’t worked so I tried with a multidimensional array but it doesn’t work either. It display an empty dropdown.

    • This reply was modified 8 years, 9 months ago by cocosay.

    I’m in the same boat here. I’ve tried the array_push and it won’t take it. I’ve tried to set the option as a variable ie.

    $hosp = "'options' =>array("
    $hosp .= "'" . $hosp_date . "' => __( '" . $hosp_date ."' ),";
    $hosp .= "),";

    and it just produces an error.

    I can’t seem to find anything on how to push variables into the options…

    Had exactly the same problem here then I realised the issue – instead of using 0-based indexing of the arrays, it requires an associative array with named keys, thus;

    using the example from @cocosay, the array was like this

    
    array_push( $stores, array('value' => $email, 'option' => $option) 
    

    but needs to be constructed like this, within a loop, as it will build up the array of options and values with named keys rather than 0,1,2 etc

    
    $stores[$email] = $option;
    

    The same is also true if passing other arrays to this function, such as custom_attributes

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘woocommerce_form_field pass array to select options’ is closed to new replies.