How to Make a WordPress Widget

As long as your WordPress theme is widget-ready, you can edit the content of your sidebar through the dashboard. In the Design > Widgets panel you can add widgets to, remove widgets from, and reorder widgets within your sidebar.

The default selection of widgets is pretty good, and there are plenty of plugins out there that will add new widgets for you to use, but what if you can’t find a widget that does what you want? Does that mean that you need to abandon your dynamic sidebar and go back to hard-coding your sidebar.php theme file?

Not at all. Instead, you can create your own sidebar widget. That way, you get the flexibility to put exactly the code that you want in your sidebar, but you can still change what sidebar items go where through the dashboard.

Let’s suppose that we want to create an author info section in our sidebar. The HTML for this might look something like this:

<li id="author-info" class="sidebaritem">
  <h2>Author Name</h2>
  <p><img src="<?php bloginfo('template_directory'); ?>/images/author.jpg" alt="Author Name" /></p>
  <p>A catchy summary of who you are and what make you so special</p>
</li>

To turn this into a widget, we just need to do three things to our functions.php theme file.

First, we need to tell WordPress that when it loads a list of sidebar widgets it should try to load our Author Info widget:

add_action('widgets_init', 'author_info_init');

When WordPress loads a list of widgets, it checks to see whether any functions have been hooked to the widgets_init action. This code hooks the author_info_init function to widgets_init, telling WordPress that when it loads a list of widgets it should call this function.

Next, we need to define the author_info_init function to register our Author Info widget so that it can appear in the list:

function author_info_init() {
  register_sidebar_widget('Author Info', 'author_info');
}

This registers the widget, naming it “Author Info” and associating it with the author_info function. The author_info function will now be called wherever our widget appears on our website.

Finally, we need to create the content of the widget by defining the author_info function so that it outputs the HTML that we want:

function author_info() { ?>
  <li id="author-info" class="sidebaritem">
    <h2>Author Name</h2>
    <p><img src="<?php bloginfo('template_directory'); ?>/images/author.jpg" alt="Author Name" /></p>
    <p>A funky description of who you are and what make you so special</p>
  </li><?php
}

Once we’ve saved and uploaded our new functions.php file, we can go to the Design > Widgets panel in our dashboard, add our Author Info widget to our sidebar, and drag-and-drop it into whatever position we want.

Of course, any code can be turned into a widget in this way, so the lack of a pre-existing widget that gives you the code that you want is never a reason to abandon your dynamic sidebar.

Leave a Reply

You must be logged in to post a comment.