小部件下拉菜单始终显示第一个选项

时间:2014-07-20 作者:Grady D

我有一个自定义小部件,我已经做了,但每当我改变下拉值,它总是恢复到第一个选项,当我保存小部件。如何让它显示用户选择的任何选项?

  // 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 个回复
SO网友:Grady D

我在WordPress支持表格上得到了答案,http://wordpress.org/support/topic/widget-dropdown-always-displays-first-option?replies=6

将函数形式替换为,

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 ) ) {
?>
并且改变了,

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

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

结束

相关推荐

从WP_LIST_CATEGORIES中删除‘Category’一词

我有以下代码:wp_list_categories();它输出我的所有类别,但是,它使它们成为列表元素的子元素,称为CATEGORIES.所以,我得到了一个无序的列表,如下所示:CATEGORIES * FASHION * DAILY FASHION CANDY * TRENDS * BEAUTY * ACCESSORIES * CELEBRITIES * LIFESTYLE 但是,我只需要:* FASHION * DAILY FA