我正在尝试创建一个接受类别的自定义最近帖子小部件,以仅显示该类别中的帖子。我在保存小部件选项时遇到问题。我做了一些调试,发现在更新函数中,$new_instance
仅包含标题选项,不通过\\ u cat。以下是表单和更新的代码:
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form($instance) {
/* Set up some default widget settings. */
$defaults = array( \'title\' => \'\', \'via_cat\' => 1);
$instance = wp_parse_args( (array) $instance, $defaults );
$cats = get_terms(\'category\');
$category_data = array();
foreach ($cats as $cat) {
$category_data[$cat->term_id] = $cat->name;
}
?>
<p>
<label for="<?php echo $this->get_field_id( \'title\' ); ?>"><?php _e( \'Title:\' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" type="text" value="<?php echo esc_attr( $instance[\'title\'] ); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id(\'via_cat\'); ?>"><?php _e( \'Category:\' ); ?></label>
<select id="<?php echo $this->get_field_id(\'via_cat\'); ?>" name="<?php echo $this->get_field_id(\'via_cat\'); ?>">
<?php
foreach ($category_data as $id => $name) {
?>
<option value="<?php echo $id; ?>"<?php echo $instance[\'via_cat\'] == $id ? \' selected="selected"\' : \'\'; ?>><?php echo $name; ?></option>
<?php
}
?>
</select>
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'title\'] = strip_tags( $new_instance[\'title\'] );
$instance[\'via_cat\'] = $new_instance[\'via_cat\'];
return $instance;
}
非常感谢您的帮助。
最合适的回答,由SO网友:onetrickpony 整理而成
您的问题是调用了错误的方法来生成name属性。应该是这样的$this->get_field_name(\'via_cat\')
此外,您可以使用wp_dropdown_categories()
, 无需重新发明车轮:
wp_dropdown_categories(array(
\'name\' => $this->get_field_name(\'via_cat\'),
\'selected\' => (int)$instance[\'via_cat\'],
));