When the widget is updated, strip_tags
is destroying the array of selected posts. A esc_sql
does the job. Also, don't use query_posts
. And finally, storing the post title is not ideal as it may change, the ID is permanent.
A working sample:
# PHP 5.3+ anonymous function
add_action( 'widgets_init', function() {
register_widget( 'Sample_Widget_SO_19246434' );
});
class Sample_Widget_SO_19246434 extends WP_Widget
{
function Sample_Widget_SO_19246434()
{
$this->WP_Widget(
'hottopics',
__('Hot Topics'),
array(
'name' => 'Hot Topics',
'classname' => 'widget-hot-topics',
'description' => __( "Description" )
)
);
}
function form( $instance )
{
if( $instance )
$select = $instance['select'];
else
$select ='';
$get_posts = get_posts( array(
'offset'=> 1,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 200,
'post_status' => 'publish'
));
if( $get_posts )
{
printf(
'<select multiple="multiple" name="%s[]" id="%s" class="widefat" size="15">',
$this->get_field_name('select'),
$this->get_field_id('select')
);
foreach( $get_posts as $post )
{
printf(
'<option value="%s" class="hot-topic" %s style="margin-bottom:3px;">%s</option>',
$post->ID,
in_array( $post->ID, $select) ? 'selected="selected"' : '',
$post->post_title
);
}
echo '</select>';
}
else
echo 'No posts found :(';
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['select'] = esc_sql( $new_instance['select'] );
return $instance;
}
function widget( $args, $instance )
{
echo 'Hello world';
}
}
Related:
• What's the difference between esc_* functions?
• How to sanitize user input?