2

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?

6

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. – SloBros Jun 15 '11 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 – user54095 Jun 12 '14 at 5:51
  • how do you save these values to the widget, and then get the selected value? – RobBenz May 10 '18 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.