1 of 17

Josh Leuze

jleuze.com

2 of 17

Building Your First Widget

3 of 17

Building Your First Widget

Why Use Widgets?

4 of 17

Using the widget API

5 of 17

Widget Class

class JL_Name_Widget extends WP_Widget {

}

6 of 17

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

);

}

7 of 17

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'];

}

8 of 17

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' );

}

9 of 17

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

}

10 of 17

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;

}

11 of 17

Register Widget

function jl_register_name_widget() {

register_widget( 'JL_Name_Widget' );

}

add_action( 'widgets_init', 'jl_register_name_widget' );

12 of 17

Widget API

http://codex.wordpress.org/Widgets_API

13 of 17

Widget In A Theme

Functions File

Include File

https://gist.github.com/JLeuze/97706990949779a1999c

14 of 17

Widget In A Plugin

Plugin File

Include File

https://gist.github.com/JLeuze/97706990949779a1999c

15 of 17

Widget As A Plugin

Plugin File

https://gist.github.com/JLeuze/475bdd6bd6095b7bdf7c

http://codex.wordpress.org/Writing_a_Plugin

16 of 17

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/

17 of 17

Go Avenge Your Father!

Or build him a widget...