How do I create a drop down menu in a widget?

This is what I do:

Static Options

<select id="<?php echo $this->get_field_id('posttype'); ?>" name="<?php echo $this->get_field_name('posttype'); ?>" class="widefat" style="width:100%;">
    <option <?php selected( $instance['posttype'], 'Option 1'); ?> value="Option 1">Option 1</option>
    <option <?php selected( $instance['posttype'], 'Option 2'); ?> value="Option 2">Option 2</option> 
    <option <?php selected( $instance['posttype'], 'Option 3'); ?> value="Option 3">Option 3</option>   
</select>

Generate with options with PHP (example)

<select id="<?php echo $this->get_field_id('posttype'); ?>" name="<?php echo $this->get_field_name('posttype'); ?>" class="widefat" style="width:100%;">
    <?php foreach(get_post_types($getposttype_args,'names') as $post_type) { ?>
        <option <?php selected( $instance['posttype'], $post_type ); ?> value="<?php echo $post_type; ?>"><?php echo $post_type; ?></option>
    <?php } ?>      
</select>

You want to change all instances of posttype to whatever field_id you want to use.

Leave a Comment