WordPress Widgets

Widgets

  • Extend the WP_Widget class which is located in wp-includes/widgets.php
  • ex.:

class Foo_Widget extends WP_Widget {
public function __construct() {
// actual widget processes
parent::_construct() {
'foo_widget', // Base ID
'Foo_Widget', // Name
array( 'description' => __( 'A Foo Widget', 'text_domain' ), );
}
public function widget( $args, $instance ) {
// outputs the content of the widget
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
echo $before_widget;
if ( ! empty( $title ) ) {
echo $before_title . $title . $after_title;
}
}
public function form( $instance ) {
// outputs the options form in the admin
if ( isset( $instance[ 'title'] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'text_domain' );
}
?>
<p>
<label for="<?php echo $this->get_field_name( 'title' ); ?>"<?php _e( 'Title:' ); ?></label>
</p>
</?php>
}
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance = array();
$instance['title'] = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
}
  • Form allows for configuration options to be set for a widget.
    • Update saves configuration options back to DB if there are options.
  • register_widget()
    • ex. add_action( ‘widgets_init’, function() { register_widget( ‘My Widget’ ); } );
  • Learn more about using namespaces.
  • Widgets can be passed outside of a sidebar by using the_widget( ‘My_Widget_Class’ );