How do I create a simple dropdown menu with 3 options in a widget? I'm using $instance to do it. How would it look in a barebones widget?
1 Answer
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.
-
You're really good at explaining, thanks a lot! This completes my plugin now.– SloBrosCommented Jun 15, 2011 at 0:21
-
i used the same solution above and its giving "Parse error: syntax error, unexpected '<' in C:\xampp\htdocs\wordpress\wp-content\plugins\genderplugin\genderplugin.php on line 100" error– user54095Commented Jun 12, 2014 at 5:51
-
how do you save these values to the widget, and then get the selected value?– RobBenzCommented May 10, 2018 at 14:04