|

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!

Similar Posts

  • |

    Do We Need ANOTHER WordPress Hosting Company?

    WordPress hosting companies are a dime a dozen these days, and if you’re going to be one, you need to differentiate yourself. This could be by offering managed WooCommerce hosting, adding on a theme shop for all customers, or creating a fantastic local development environment that integrates perfectly. When it comes to WordPress host WPX, there are 3 features that differentiate them from competitors.

  • 3 Ways to Make the Most of Your WordCamp US Experience

    WordCamp US 2019 is next week and I’m getting excited. It’s the biggest US-based conference for people in the WordPress community and at this point, it feels a lot like a college reunion to me. But there are also goals I’d like to accomplish while I’m there. If you’re spending your own money to get…

  • | |

    Eliminating Slack as a Distraction to Work Better

    One of my goals is to read 21 books this year, and I’m doing super well so far. After finishing the super dense (and very thought provoking) Homo Deus, I’m flying through It Doesn’t Have to be Crazy at Work. While the hubris of Jason Fried used to drive me crazy, I’ve read all of…

  • I’m Speaking about WordPress on Saturday in Scranton!

    Come on down to the Vintage Theater at 9am Saturday to see me speak about the basics of WordPress! My talk is part of a 24 Hour bonanza that’s going on from Friday at 9pm to Saturday at 9pm. I will include art, music, movies, tech, and more! The Vintage Theater is located at 326 Spruce…

  • My Morning Routine & Free New eBook!

    A month or so ago my friend Jonothon Kneeper reached out to me about my morning routine, mentioning that he was compling data for a book he was writing. I’m happy to say the book, Win Your Day, is live on Amazon and you can get it for free today (Feb. 4th)! It has lots of…

  • |

    QT: Increase the WordPress RSS Widget Refresh Rate

    Note: This article was published while I was in my early 20s. I was much younger and dumber. Please don’t hold it against me. One of the perils of having a 20+ year old website!While working on the redesign to this blog, I wanted to add the “Interesting Stuff” column you see just to the…

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.

Comments are closed.