1

I have a custom widget that I have made but whenever I change the dropdown value it always reverts to the first option when I save the widget. How can I have it display whatever option the user selects?

  // update widget
  function update($new_instance, $old_instance) {
        $instance = $old_instance;
        // Fields
        $instance['category'] = strip_tags($new_instance['category']);
       return $instance;
  }

  // widget form creation
  function form($instance) {
    // Check values
    if( $instance) {
         $category = esc_attr($instance['app_category']);
         $instance['category'] = strip_tags( $new_instance['category'] );
    } else {
         $category = '';
    }
    //Set up some default widget settings.
    $defaults = array( 'category' => '');
    $instance = wp_parse_args( (array) $instance, $defaults );
?>
    <!-- Category Select Menu -->
    <p>
      <label for="<?php echo $this->get_field_id('category'); ?>"><?php _e('App Category: ', 'AppManager_plugin'); ?></label>
      <h1><?php echo $category ?></h1>
      <h1><?php echo $instance['category'] ?></h1>
      <select id="<?php echo $this->get_field_id('category'); ?>" name="<?php echo $this->get_field_name('Category'); ?>" >
        <?php foreach(get_terms('app_category','parent=0&hide_empty=0') as $term) { ?>
          <option <?php selected( $instance['category'], $term->term_id ); ?> value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
        <?php } ?>
      </select>
    </p>

1 Answer 1

0

I got an answer on WordPress Support forms, http://wordpress.org/support/topic/widget-dropdown-always-displays-first-option?replies=6

Replaced function form with,

function form( $instance ) {
    // Check values
    $category = isset( $instance['category'] ) ? (int) $instance['category'] : '';
    $terms = get_terms( 'app_category', 'parent=0&hide_empty=0' );
    if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
?>

And changed,

name="<?php echo $this->get_field_name( 'Category' ); ?>"

to

name="<?php echo $this->get_field_name( 'category' ); ?>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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