• Hello guys,

    I am trying to add a select field to the woocommerce product page with dynamic number of options (defined in the settings). For a fixed number of options I would use this code:

    'options' => array(
    'one'   => __( 'Option 1', 'woocommerce' ),
    'two'   => __( 'Option 2', 'woocommerce' ),
    'three' => __( 'Option 3', 'woocommerce' )
    )

    So it is something like option_value => __( option_name, text-domain). This works perfectly. However, I am running into problems when I try to adjust the code for dynamic number of options. What I have now is:

    function woo_add_custom_fields() {
        global $woocommerce, $post;
        $db_options = get_option('my_option');
        echo '<div class="options_group">';
        
        $options = explode(",", $db_options);
    
        woocommerce_wp_select( 
            array( 
                'id'      => '_select', 
                'label'   => __( 'Select field', 'woocommerce' ), 
                'value' => get_post_meta( get_the_ID(), 'option', true ), 
                'options' => $options )
            );
        echo '</div>';
    }
    
    function woo_add_custom_fields_save( $post_id ) {
    	$option = $_POST['_select'];
    	update_post_meta( $post_id, 'option', esc_attr( $option ) );
    }

    As a result, I do get the select fields, but the options don’t have a proper option_value and don’t have a text-domain. How can I solve this problem?

    Many thanks in advance for your help!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    I cannot comment on how to use woocommerce_wp_select(). You should ask in the WC dedicated support forum for that. Unfortunately, many topics go unanswered there.

    You don’t need a special WC function to build a form field. I cannot give specifics without knowing what the nature of the option value saved is. Generally speaking though, if it’s an array of something, use foreach to step through each array item and do something with it to output each select option.

    First though, you output the non-repeating select tag. Then do the foreach, which will loop for each item in the array, no matter the number. After outputting all the option tags and outside the foreach loop, output the closing select tag. Maybe like this:

    <select>
    <?php foreach ( $db_options as $key => $value ) {
       echo "<option value=\"$key\">$value</option>\n";
    } ?>
    </select>
Viewing 1 replies (of 1 total)

The topic ‘Populating select field with options’ is closed to new replies.