Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 7 • Making the Most of WordPress Plugins 205


}
}
register_widget( 'SmashingWidget' );

In this example, you extend the WP_Widget class with the SmashingWidget widget. The first
function, which is just function SmashingWidget(), is the actual widget with the func-
tionality you want, so that’s where the action is. The widget(), update(), and form()
functions are necessary to get the widget to behave the way you want. Obviously, you wrap it up
by registering the widget with register_widget(). Both the Cancel link and the Submit
button are built in to the Widgets API, so you needn’t worry about them when it is time to save
whatever changes you’ll let your users meddle with.

CREATING A WIDGET
This section walks you through creating a simple widget. This widget will output some text
to say hello to the visitor, and you’ll also be able to rename the heading from within the
admin interface:


  1. Remember, all this code is within a plugin file, which is PHP and has the plugin identify-
    ing header. Unless you have a plugin you want to add this functionality to, you should
    create a brand-new one with an appropriate name.


Start with the widget class:


class SmashingHello extends WP_Widget {

The widget is named SmashingHello, so you can probably tell what’s coming.



  1. Next, you get the widget function:


function SmashingHello() {
parent::WP_Widget( false, $name = 'Smashing Hello' );
}


  1. Remember, you need widget(), update(), and form() to make cool things happen.
    This is the next step, starting with widget():
    function widget($args, $instance) {
    extract( $args );
    ?>
    <?php echo $before_widget; ?>
    <?php echo $before_title
    . $instance['title']
    . $after_title; ?>
    Well hello there! Ain't that just Smashing?
    <?php echo $after_widget; ?>
    <?php
    }


You take widget() and extract the arguments. Notice the $before_widget,
$after_widget, $before_title, and $after_title settings. These shouldn’t be
changed unless necessary. They are controlled by the Widgets API and default theming,
so they make things look good.

Free download pdf