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

(avery) #1

206 PART III • Using Plugins with WordPress


So what happens? You echo $before_widget and then $before_title, without
telling them to do anything fancy, so they’ll just pick up the default code. Then there’s the
$instance title, which is the title you’ll use as an input field in the widget interface
within admin, so people can write whatever they want there. Then you’re done with the
title, getting to $after_title, and then there’s your lovely text that the widget will
display: ̋Well hello there! Ain’t that just Smashing?” Not high prose, of course, and you
can put just about anything here — a WordPress loop query or whatever. Finally, the
widget is all over, and you get $after_widget.
Again, these before and after bits are to make the widget behave the way the theme
wants them to. This is something the theme designer can control, so if you want to keep
your widget cross-compatible, you can stick to the defaults and worry about how it looks
in the design.


  1. Moving on, you need to make sure that the widget is saved properly when updated:
    function update($new_instance, $old_instance) {
    return $new_instance;
    }
    This is easy because update() takes only $new_instance and $old_instance.
    Naturally, you want to return $new_instance, which is whatever you changed. You
    may want to do some tag stripping with strip_tags() here if the kind of widget
    you’re creating may run into some nasty HTML stuff. That’s easy; just do something like
    this for an input field named 'music':
    $instance['music'] = strip_tags( $new_instance['music'] );
    See strip_tags() at work here? It makes sure that no stray HTML code gets through.
    Very handy.

  2. Now add one more setting to change the widget title:
    function form( $instance ) {
    $title = esc_attr( $instance['title'] );
    ?>




    }
    The keys here are get_field_name() and get_field_id(). They handle which
    field does what. And then, when you’ve built your pretty little widget settings form, just
    save it (with the Widgets API automatically created Save button), and it does the trick.

  3. Finally, you need to close the class with a curly bracket and register the widget:

Free download pdf