I try to create my own widget for my plugin after codex too .
This is what I still have. It works and saves and displays the saved parameter value.
<?php
$colors = array('red', 'blue', 'yellow');
update_option('sample_widget', $colors);
add_action( 'widgets_init', create_function( '', 'register_widget( "Sample_Widget" );' ) );
class Sample_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'foo_widget',
'Sample Widget',
array( 'description' => __( 'This is a description of the sample widget', 'text_domain' ), )
);
}
public function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
$color = apply_filters( 'widget_title', $instance['color'] );
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
echo 'the selected color is ' . $color . '<br />';
echo $after_widget;
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['color'] = $new_instance['color'];
return $instance;
}
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'text_domain' );
}
if ( isset( $instance[ 'color' ] ) ) {
$selected_color = $instance[ 'color' ];
}
$colors = get_option('sample_widget');
?>
<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>
<select name="<?php echo $this->get_field_name( 'color' ); ?>" id="<?php echo $this->get_field_id( 'color' ); ?>">
<option value="">Select...</option>
<?php foreach($colors as $color) echo '<option value="' . esc_attr( $color ) . '" ' . ($color == $selected_color ? 'selected="Selected"' : '') . '>'. $color .'</option>'; ?>
</select>
</p>
<?php
}
}
I have two questions:
- What is
id="<?php echo $this->get_field_id( 'color' ); ?>"for? I deleted this part of the line and it works fine. I put it to just copy the working codex code. - In the constructor, the first parameter in
parent::__construct()is the base identifier. Could this be any string value? I changed it to something else from foo_widgetand it looks like it works.
Thanks for your information.
source
share