WordPress Tutorial on How to Create a Theme Widget
In this tutorial, we will learn how to create a WordPress Theme Widget that you can drag and drop to a widget area of the theme. We are using a clone of the Twenty Fourteen theme which we had called “Twenty Fourteen Custom”. See how we created a clone of a theme.
We will work with the default Hello Dolly plugin that comes with WordPress which randomly display line of lyric from the Hello Dolly song.
To get the “Hello Dolly Lyric” widget to show up in “Appearance -> Widgets”, we have to call wp_register_sidebar_widget whose reference can be found here.
We put this call in the plugin file which is …
/wp-content/plugins/hello.php
At the bottom of this file, we put the following code …
The four parameters that we passed into wp_register_sidebar_widget are ..
1) The unique id for the widget
2) the name of the widget
3) the callback function that renders the widget
4) and the options
We arbitrarily named our callback function hellodolly_widget which is defined as shown above. Basically, the callback function is a bunch of echo statements that renders the widget on the front-end. First we extract $args. Then we echo $before_widget. These are standard variables that the callback function has access to. So keep the names as shown.
Then we echo an arbitrary title for the widget with $before_title prepended to it and $after_title appended to it.
Then comes the meat of the function which is to echo a random lyric line from the Hello Dolly song. The hello.php plugin file already has function called hello_dolly_get_lyric() function the returns this. So we just echo the return of this function.
Finally, we echo $after_widget.
After dragging the widget to the “Content Sidebar” widget area, we now see the Hello Dolly lyric render on the sidebar of a post …
This is very basic introduction to widget development. So this widget has no options. And you can only have one instance of this widget.