// Creates a Simple_Widget.
class Simple_Widget extends WP_Widget{
// Constructor
public function __construct(){
$widget_options = array(
'description' => 'A Simple Widget with limited use.',
'classname' => 'simple-class',
);
parent::__construct('simple_widget', 'Simple Widget', $widget_options );
}
// Outputs the widget content on the front-end
public function widget( $args, $instance ){
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
$text = apply_filters( 'widget_text', $instance['text'] );
echo $before_widget;
echo (!empty( $title )) ? $before_title . $title . $after_title : '';
echo (!empty( $text )) ? $text . $after_widget : '';
}
// Outputs options form in the WordPress admin
public function form( $instance ){
isset($instance[ 'title' ]) ? $title = $instance[ 'title' ] : $title = __( 'Simple Title', 'xxx_domain' );
isset($instance[ 'text' ]) ? $text = $instance[ 'text' ] : $text = __( 'Simple Text', 'xxx_domain' );
<p>
<label for="<?php echo $this->get_field_name( '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 for="<?php echo $this->get_field_name( 'text' ); ?>"><?php _e( 'Text:' ); ?></label>
<textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>"><?php echo $text; ?></textarea>
</p>
}
// Saves or updates widget data. Replaces old instances with new instances.
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['title'] = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['text'] = ( !empty( $new_instance['text'] ) ) ? strip_tags( $new_instance['text'] ) : '';
return $instance;
}
}
// register the Simple Widget
function register_simple_widget() {
register_widget( 'Simple_Widget' );
}
add_action( 'widgets_init', 'register_simple_widget' );
Code for a simple WordPress widget with a title field and a text area.