我的Wordpress插件出现问题。我试图制作一个按钮小部件,后端有多个选项。我的问题是标题正在保存,而不是select标签中的选项。 这是一段代码:
<code>add_action( 'widgets_init', function(){
register_widget( 'Button_Widget' );
});
class Button_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'Button_Widget', // Base ID
__('♦ Button', 'text_domain'), // Name
array('description' => __( 'Insert a button', 'text_domain' ),) // Args
);
}
/**
* Front-End Widget
*/
public function widget( $args, $instance ) {
//coming soon
}
/**
* Back-end widget form.
*/
public function form( $instance ) {
?>
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'text_domain' );
}
?>
<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( $title ); ?>">
</p>
<p>
<label>Animaton:</label>
<select>
<option value="slide">Slide</option>
<option value="fade">Fade</option>
<option value="bounce">Bounce</option>
</select>
<label>Color:</label>
<select>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
</select>
</p>
<?php
}
}
答案 0 :(得分:2)
您需要向select元素添加一个id,然后在widget中实现更新功能:
function update($new, $old){
$instance = $old;
$instance["select_id_1"] = $new["select_id_1"];
return $instance;
}
答案 1 :(得分:0)
我找到了解决方案。
以下是WordPress后端的代码:
<p>
<label for="<?php echo $this->get_field_id('text'); ?>">Color:
<select class='widefat' id="<?php echo $this->get_field_id('color'); ?>"
name="<?php echo $this->get_field_name('color'); ?>" type="text">
<option value='Green'<?php echo ($color=='Green')?'selected':''; ?>>
Green
</option>
<option value='Red'<?php echo ($color=='Red')?'selected':''; ?>>
Red
</option>
<option value='Blue'<?php echo ($color=='Blue')?'selected':''; ?>>
Blue
</option>
</select>
</label>
</p>
新的更新功能:
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['animation'] = $new_instance['animation'];
$instance['color'] = $new_instance['color'];
return $instance;
}
为了确保一切正常,您还可以输出值:
if (!empty($animation))
echo $animation;
if (!empty($color))
echo $color;