I’m trying to create a custom widget for my plugin and following the codex.
This is what I have so far. It’s working and saves and displays the saved option value.
<?php
/**
* Plugin Name: Sample Widget
*/
$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' ), ) // Args
);
}
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 removed this part of the line and it seems to work fine. I placed it to just copy the codex working code. - In the constructor, the first parameter in
parent::__construct()
is a base ID. Could this be any string value? I changed it to something else fromfoo_widget
and it seems to work.
Thanks for your info.
The
id="<?php echo $this->get_field_id( 'color' ); ?>"
is to generate a unique ‘id’ value for this option. Typically this is so the object can be manipulated via JS.The
id_base
offoo_widget
is a Root id for all widgets of this type. It is an Optional Base ID for the widget, in lower case, and if left empty a portion of the widget’s class name will be used. It has to be unique. This will be appended to with the individual widget’s ID number i.e.foo_widget-001
Hope this helps you!