Creating WordPress Widgets: The Complete Guide

widgets wall

Over the years, we’ve written a lot about WordPress. At one time or another, we’ve covered most of the knowledge that we use as professional WordPress developers. Today we turn our attention to how to create a widget with WordPress.

Introducing Courses

We believe linking related articles together into Courses will really help your WordPress learning.

This being a blog, though, a lot of that information is pretty deep on the site. So we’re excited to debut something that we think will really help your WordPress learning: Courses! Each WPShout Course will pull a number of related WPShout articles together to give a coherent treatment of a single major topic in WordPress development. The Course itself will clarify the the key points of each article and the relationships between articles, for both a simple and in-depth exploration of the subject.

Today’s course is on working with widgets. If you’ve ever wanted to create widget areas (sidebars), or to fill your widget areas with custom-built widgets, this course is for you!

Thanks for Reading WPShout!

Before we dive into our first Course, we want to thank you for reading WPShout, and invite you to do a few things:

  1. Please comment freely on our articles with any questions, corrections, suggestions, etc. We love to hear from readers—it helps us understand how you guys are interacting with what we write.
  2. If there’s a topic in WordPress you’d like us to cover, tell us about it! We love to dive into the parts of WordPress that people would like the most help with. You can contact us directly at contact@wpshout.com.

Onto today’s Course: our full guide to creating your own WordPress widgets and widget areas.

1. Understanding the Basics of Object-Oriented Programming

WordPress’s widgets system (or “Widgets API”) makes use of a specific programming style called object-oriented programming, or OOP. Every WordPress widget is actually a WP_Widget Object—meaning an individual instance of the broader WP_Widget Class.

So our first step to program WordPress widgets is to understand the basics of object-oriented programming (OOP).

The Concepts of Object-Oriented PHP You Need to Understand for WordPress Development

Key Point: Classes and Objects

A Class is an abstract description of a type of thing. Once you’ve defined a Class, you create actual Objects of that class. The article uses the example of a Chair class:

// Creating the Chair class
class Chair {
    // Here we list important elements that all Chairs have,
    // like "height" and "color"
}

// Creating a Chair object
$mychair = new Chair;

Key Point: Properties and Methods

A Class’s properties define attributes that each Object has, and a Class’s methods define functions that each Object can perform. For example, each chair might have a color property, and a rock() method:

class Chair {
    public $color;
    public function rock() {
        // Details of the rock() method
    }
}

While all chairs have the color property, we decide the actual color of each individual Chair object. One Chair might be green, while another might be red:

$mychair = new Chair;
$mychair->color: 'green';

$secondchair = new Chair;
$secondchair->color: 'red';

And when we’ve created our Object, then we can call its methods:

$examplechair = new Chair;

// Call the rock() method on the new object
$examplechair->rock();

If you understand the raw basics of OOP—Classes, Objects, Properties, and Methods—you’re ready to get into creating WordPress widgets.

2. Creating a Very Basic WordPress Widget

A widget is something—it can be anything!—that you drop into a WordPress widget area, such as a sidebar. This article covers creating a very basic, but functional, widget.

A Complete Guide to Making Your First WordPress Widget

Key Point: Register Your Widgets in a Plugin

Most widgets are best placed in a plugin—not in your theme—because you don’t want them to disappear if you switch themes. The article links to our tutorial on writing plugins—it’s much easier than you might think.

Key Point: The Minimal Code for a Widget

The code below, placed into the main PHP file of a properly registered plugin, will create a working widget. When you place that widget into a widget area like your sidebar, it’ll output the text “First WordPress Widget! Yay!” wherever you’ve put it.


// Create the First_WordPress_Widget class
class First_WordPress_Widget extends WP_Widget {
    public function widget( $args, $instance ) {
        echo 'First WordPress Widget! Yay!';
    }
}

// Register the new widget at the widgets_init action hook
add_action( 'widgets_init', 'first_wp_widget');
function first_wp_widget(){
     register_widget( 'First_WordPress_Widget' );
}

3. Creating A Complex, User-Editable WordPress Widget

Most widgets will want to accept user input: for example, a “social follow” widget will want to ask the user the addresses of her social media accounts and which accounts to list. This article goes deep into a fully functional “Now Playing” widget that lets the user put a playable “favorite song” link in her sidebar.

Creating Dynamic, User-Editable WordPress Widgets

Key Point: form(), update(), and widget()

The Widgets API isn’t as simple as it could have been, and the code for this widget (or any really useful widget) is complex and extensive. As you read through the article, remember that the code is organized into three functions of primary importance: form(), update(), and widget().

Each of these functions is a method of the Class we’re defining, which in this case is WPShout_Favorite_Song_Widget. All of the heavy lifting takes place within the class definition for WPShout_Favorite_Song_Widget itself.

So although the plugin’s full code at the bottom of the article looks scary, there are really only four major pieces:

  1. Hooking into widgets_init, as we covered above
  2. Within the definition of WPShout_Favorite_Song_Widget, writing out the specifics of form()
  3. Within the definition of WPShout_Favorite_Song_Widget, writing out the specifics of update()
  4. Within the definition of WPShout_Favorite_Song_Widget, writing out the specifics of widget()

There’s a lot here, so take your time seeing how the pieces fit together. And feel free to take the fully-working code and adapt it to your own needs—that can be a great way to learn and to get results quickly.

4. Registering Your Own Widget Areas

Like socks go in a sock drawer, widgets go into widget areas. This article covers how to “widgetize”—create widget areas for—all different areas of your site, from your sidebar to your header to your footer to your homepage.

All You Need to Know About Making Widget Areas in WordPress Themes

Key Point: “Sidebar” and “Widget Area”

A sidebar is one type of widget area. Some widget areas are located in the theme’s sidebar, but not all are.

The relationship is as follows: a sidebar is one type of widget area. Some widget areas are sidebars—meaning simply that they show up in their theme’s sidebar, a column next to the main post content—but not all are.

However, WordPress’s own code often uses “sidebar” when it means “widget area,” because that code was written back when sidebars were the only kind of widget area.

Key Point: Widget Areas Go in Themes

Because a widget area is part of how your site will display—and not the data the site contains—it’s something to program in your theme rather than a plugin. That means you’ll be writing the PHP for your widget area into your theme’s functions.php.

Key Point: register_sidebar( $args )

The main function to create a WordPress widget area is simple: register_sidebar().

That function comes along with a lot of options, and the way you set these options is to create an array (by convention, generally named $args) that defines values for all these options. A very simple call to register_sidebar() would look like this:

$args = array(
    'name'          => 'Widgetized Sidebar',
    'id'            => "widgetized-sidebar",
);
register_sidebar( $args );

For a real widget area, the article gives a much fuller set of options for $args.

Key Point: Hooking into widgets_init

Your call to register_sidebar() needs to find its proper place in WordPress’s loading sequence, and it does this with WordPress’s hooks system. The action hook for, so the full code to register a sidebar would look as follows:

function my_theme_widgets_init() {
    $args = array(
        'name'          => 'Widgetized Sidebar',
        'id'            => "widgetized-sidebar",
    );
    register_sidebar( $args );
}
add_action( 'widgets_init', 'my_theme_widgets_init' );

Key Point: Inserting the Registered Widget Area into Your Theme with dynamic_sidebar()

Once you’ve registered your widget area, you’ll need to put it “where it goes” in your theme—into your sidebar area, your footer, or what have you. The key function that does this is dynamic_sidebar(). Wrapped up in the proper checks that the widget area exists and has widgets in it, as well as some example HTML markup, that looks as follows:

<?php if ( is_active_sidebar( 'widgetized-sidebar' ) ) : ?>
    <div id="secondary" class="widget-area" role="complementary">
        <?php dynamic_sidebar( 'widgetized-sidebar' ); ?>
    </div><!-- #secondary -->
<?php endif; ?>

Now You Get WordPress Widgets!

Thanks for reading our first WPShout Course. We’re really excited about Courses as a method of covering complex WordPress topics that takes you from start to finish and helps your knowledge build on itself.

Sooo, how’d it work for widgets and widget areas? Did you manage to create your own WordPress widgets? We’d love to hear your thoughts and questions below

Image credit: Nicolas Guyon


12 Responses

Comments

  • Amit Ramani says:

    Great detailed article. I need to define a widget that shows up only on the shopping cart page (Woocommerce). Currently I use a full width template for the cart page. How do I implement this widget area so it shows up only on the cart page and nowhere else on the site?

    • You can try using Widget Logic plugin to set conditional widget

      https://wordpress.org/plugins/widget-logic/

      • Amit Ramani says:

        Towhidul, I am aware of the use of plugins to achieve that. The original guide focuses on how to do widgets using code.

    • fredclaymeyer says:

      Hi Amit,

      Good question! Once you’ve registered your widget area, the easiest way to meet your goal would be to modify your Cart page template directly in your theme. WooCommerce supports this – check this article for details.

      You can leave the Cart page template mostly the same, but you’ll place the code to include your widget area directly into that template, wherever you want it to show up. The include code is the code that looks something like:

      <?php if ( is_active_sidebar( 'widgetized-sidebar' ) ) : ?>
      <div id="secondary" class="widget-area" role="complementary">
      <?php dynamic_sidebar( 'widgetized-sidebar' ); ?>
      </div><!-- #secondary -->
      <?php endif; ?>

      Is that helpful?

  • surja says:

    Very good article, this new “Course” feature is invaluable for new WordPress developers. There is a huge number of WP development tutorials around the web and on this site but, as you have correctly noted, they are not always easy to find. This new feature should help in that direction. Hope to see a course on database related stuff, with some good examples, e.g. creating user custom profiles, updating profiles and retrieving them for viewing etc.

    Thank you :)

    • fredclaymeyer says:

      Belatedly: Thanks so much, Surja! That means a lot.

      We’ve noted your course request—we’ll let you know if we’re able to put something together on that topic!

  • Alamin Topu says:

    Great articles. Really, it is very helpful for me.

Pingbacks

Add a Comment

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