|

Excerpt from Building WordPress Themes from Scratch

Building WordPress Themes from ScratchRecently my first book, Building WordPress Themes from Scratch, made its way back onto the market. In this book, I teach you how to use WordPress as well as how to leverage the API to create your own custom themes, plugins, and content types. Here is an excerpt from the book. Enjoy!

Creating Widgets

Widgets are a great way to add secondary content to your website. While you can do a lot with the text widget and generally find a plugin that will give you the widget you’re looking for, there is still plenty of opportunity to develop ones specific to your site. In this theme, we’re going to develop one to display a featured business right from the sidebar.

Go ahead and open up the functions.php file. We’ll start by including a file called director-widgets.php:

Now let’s create that file, and subsequently, our featured business widget. Add director-widgets.php to the /director/ folder and add this code:

// widget actual processes
      }
       public function form( $instance ) {
            // outputs the options form on admin
      }
      public function update( $new_instance, $old_instance ) {
            // processes widget options to be saved
      }
       public function widget( $args, $instance ) {
            // outputs the content of the widget
      }
}
register_widget( 'Director_Featured_Widget' );
?>

This is a slight modification of what we find in the WordPress Codex. Let me explain each function quickly before we get any farther.

First, we have a class called Director_Featured_Widget that extends the built-in WordPress class WP_Widget(). This class has four functions we can use when building our class:

  1. __construct(): If you’re familiar with object-oriented programming (OOP), you’ll know that this is the constructor. This is essentially how we initialize our object. In this case, we will define our widget using the constructor.
  2. form(): If we are building widget options for the user to customize the widget, we would do that here. We will be using this only to change the title of the widget.
  3. update(): This is how our class would process any form options from the admin panel. Again, we will use this only to change the title of the widget.
  4. widget(): Here is where all of our magic will happen. This is the function that’s used to display our widget to the user.

Alright – now let’s fill in the functions we will be using, starting with __construct(). All filled in, that function should look like this:

public function __construct() {
parent::__construct(
            'director_featured_business',
            'Featured Business',
            array( 'description' => __( 'Displays the Featured Business'))
      );
}

What we’re doing in our constructor is calling our class’s parent’s constructor – that is, the constructor defined in WP_Widget. This saves us from writing our own function that would do the same exact thing.

We are sending three arguments to the parent constructor:

  1. A unique ID for the widget
  2. The title of the widget
  3. An array of other settings. We’re only sending the description of the widget (which will show up in the admin).

Next, we have our two interactive functions, which I’ll show together:

public function update( $new_instance, $old_instance ) {
      $instance = array();
      $instance['title'] = strip_tags( $new_instance['title'] );
       return $instance;
}
public function form( $instance ) {
      $title = (isset( $instance[ 'title' ])) ? $instance[ 'title' ] : 'Featured Business';
?>
      

                 

Even though our functions are in opposite order, I’d like to start with form() first. In  the first line…
$title = (isset( $instance[ 'title' ])) ? $instance[ 'title' ] : 'Featured Business';
…we have a conditional assignment that will set title to either be the title value defined by the user, or the default value of “Featured Business.” $instance is the array of values used manipulate our widget.

The next section of the function prints the input box used for the Title. You’ll see a set of similar functions beginning with $this -> get_field_. These are functions that our class inherited from WP_Widget. It uses the field name (which gets defined as we call it – that is, if it doesn’t exist, create it) as the slug, using it the same way slugs are used throughout WordPress.

Since there is a singular “save” button that is include on every WordPress widget in the admin, we also have a function within our class to save & sanitize the information. That function is update().

This is a pretty simple function. We’re creating a new array for a freshly cleaned set of data. But, since in this case we’re only editing one value – title, that’s the only value we have to clean. The argument $new_instance has the new data from the user, and we use PHP’s built-in strip_tags() to remove any possibly malicious data. One thing to note is that we must match up the keys in $instance with the keys in $new_instance. If we don’t, everything will break.

The first four lines of this function handle getting and displaying the title.  The array $args contains all of the information related to the widget; this includes any values that we’ve modified through form()/update(), and the information we set when registering the sidebar ($before_widget, $after_widget, etc).  After using PHP’s built-in extract() function to make the key => value pairs in $args instance variables, we use WordPress’s apply_filters() function to prepare our title for displaying on the front end.  We then print the markup that goes before the widget ($before_widget) as defined in the functions.php file, where our sidebar is registered. In the next line, we do the same thing for the title; if it exists, print it wrapped in the markup that should go before and after the title, as defined where the sidebar is registered.

To read more about creating widgets and building complete WordPress Themes, order Building WordPress Themes from Scratch today!

4 Comments

  1. I figured it out. The download site name on the kindle edition is missing a “-“.

  2. I just purchased this Book from amazon. And after reading this, it looks WordPress isn’t that difficult or complicated, that i thought it to be.

    Thanks envato and casabona for this great book.

Leave a Reply

Your email address will not be published. Required fields are marked *