WordPress select dropdown list in widget

Ok, I’m developing my own widget and I’ve a HUGE problem.

I don’t know how to fetch and eventually save html selects value.

Simple example:

/* initialize TITLE */
function widget( $args, $instance ) {
        extract( $args );
        $title = apply_filters('widget_title', $instance['title'] );

(...)

/* update code for TITLE */
    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance['title'] = strip_tags( $new_instance['title'] );

(...)

/* creating TITLE field in widgets admin area */

 <p>
    <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label>
    <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" type="text" style="width:100%;" />
 </p>

(...)

OK. Now when I type

<?php echo $instance['title'] ?>

It’s going to show my title!

But I have this list:

<label for="<?php echo $this->get_field_id( 'example' ); ?> "><?php _e('Map type:', 'example'); ?></label>
<select id="<?php echo $this->get_field_id( 'example' ); ?>" name="<?php echo $this->get_field_id( 'example' ); ?>">
     <option value="supervalue" selected="selected">Super Value</option>
</select>

And

<?php echo $instance['example'] ?>

Gives NOTHING. I’ve been looking everywhere including default-widgets.php but I don’t understand a word since all default plugins use mostly dynamically generated option lists.

I’ve used only one item list, but in fact it’s longer, I’m not sure how to save the selected element also, since I don’t know how to access this element’s value.

Any ideas? I spent the whole day on this, getting totally mad slowly.

[edited]

I didn’t show you the update function because as I mentioned above I use the same update code for each function.

 function update( $new_instance, $old_instance ) {

    $instance = $old_instance;
    $instance['example'] = strip_tags( $new_instance['example'] );    

    return $instance;

}

2 Answers
2

See my comment above…you’re using get_field_id() on the name-attribute, where it should be get_field_name().

get_field_id() returns 'widget-'.$this->id_base.'-'.$this->number.'-'.$field_name,
whereas
get_field_name() returns 'widget-'.$this->id_base.'[' . $this->number . '][' . $field_name.']'

Leave a Comment