Josh Leuze
jleuze.com
Building Your First Widget
Building Your First Widget
Why Use Widgets?
Using the widget API
Widget Class
class JL_Name_Widget extends WP_Widget {
}
Setup Widget
function __construct() {
parent::__construct(
'name', // Base ID
__('Name Widget', 'jl_name_widget'), // Name
array( 'description' => __( 'A widget for adding your
name.', 'jl_name_widget' ), ) // Args
);
}
Widget Display
public function widget( $args, $instance ) {
$jl_name = apply_filters( 'widget_title',
$instance['jl_name'] );
echo $args['before_widget'];
echo $args['before_title'] . '<span>Hello</span> my
name is...' . $args['after_title'];
if ( ! empty( $jl_name ) ) {
echo '<p>' . $jl_name . '</p>';
}
echo $args['after_widget'];
}
Widget Form, Set Default Name
public function form( $instance ) {
if ( isset( $instance[ 'jl_name' ] ) ) {
$jl_name = $instance[ 'jl_name' ];
}
else {
$jl_name = __( 'Inigo Montoya', 'jl_name_widget' );
}
Widget Form, Add Name Form
?><p><label for="<?php echo $this->get_field_id( 'jl_name' ); ?>"><?php _e( 'Name:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'jl_name' ); ?>" name="<?php echo $this->get_field_name( 'jl_name' ); ?>" type="text" value="<?php echo esc_attr( $jl_name ); ?>"></p>
<?php
}
Sanitize & Save
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['jl_name'] = ( ! empty( $new_instance['jl_name'] ) ) ? strip_tags( $new_instance['jl_name'] ) : '';
return $instance;
}
Register Widget
function jl_register_name_widget() {
register_widget( 'JL_Name_Widget' );
}
add_action( 'widgets_init', 'jl_register_name_widget' );
Widget API
http://codex.wordpress.org/Widgets_API
Widget In A Theme
Functions File
Include File
https://gist.github.com/JLeuze/97706990949779a1999c
Widget In A Plugin
Plugin File
Include File
https://gist.github.com/JLeuze/97706990949779a1999c
Widget As A Plugin
Plugin File
https://gist.github.com/JLeuze/475bdd6bd6095b7bdf7c
http://codex.wordpress.org/Writing_a_Plugin
My Favorite Widgets
Image Widget by Modern Tribe
http://wordpress.org/plugins/image-widget/
Flexible Posts Widget by Dave Ellenwood
http://wordpress.org/plugins/flexible-posts-widget/
Monster Widget by Michael Fields
http://wordpress.org/plugins/monster-widget/
TinyMCE Widget by Black Studio
http://wordpress.org/plugins/black-studio-tinymce-widget/
Go Avenge Your Father!
Or build him a widget...