After creating my first widget, making lots of mistakes and doing a lot of hunting for information, I decided it would be very helpful to walk you through creating a widget with several options in an easy-to-read manner. I spent a lot of time looking for information online and after doing a lot of self-teaching, I’ve got it down, so I wanted to centralise all this knowledge for your benefit.
Widgets were introduced in version 2.2 and allow users to add elements to their sidebars that can query the database and run PHP. For example, my sidebar includes widgets that display recent posts, popular posts and upcoming posts. Incidentally, I’m going to use the example of my upcoming posts widget (which I released into the WordPress directory) to walk you through this tutorial.
Consider what you’re trying to achieve
It’s important to put this brainstorming ahead of time, so that you can lay things out sensibly and neatly. Consider what you’re trying to display and what you’ll need in order to achieve that. In the case of my plugin, I needed to collect the following information:
- The title of the sidebar widget
- The number of upcoming that the user wants to display
- Whether the user wants to display scheduled posts, drafts, or both
- Whether the user wants to display a link to a newsletter signup page
- The URL of the newsletter signup page
- Whether the user wants to display a credit link (the WordPress rules require that you ask permission for such links)
Once I knew what information I needed to collect, I assigned a unique identifier to each variable. You can use underscores, but you can not use spaces in these names. So for me, I labeled the variables as follows to match up with the list above:
Making these descriptive will help you decipher your code. Now you’re in a position to start putting the actual code together.
Creating the plugin file
In order to create the widget, we need to create a plugin which will register the widget. If you want to develop this on your live site, log in to your hosting control panel and navigate to /wp-content/plugins/. Otherwise, just create a folder on your hard drive and develop it locally.
Create a new folder that will describe your plugin. Make it a unique name so that it doesn’t conflict with other plugins. For example, mine is ‘soup-show-off-upcoming-posts’. Using something generic like ‘upcoming’ might have caused problems with other plugins. Once you’ve created the folder, create a file inside the folder with the same name as the folder (it doesn’t have to be the same, but again, make it obvious what plugin and function it is for). For my plugin, the file name is ‘soup-upcoming-posts-widget.php’.
Now you’re going to open your file up for editing. You can either do this in your web host’s file manager, or in the WordPress plugin editor (Plugins > Editor). The first section in the plugin file will be some information about the plugin that WordPress can read. WordPress will then use this information for a variety of uses, like listing the plugin in the plugin list, or the WordPress repository. The format of this information is as follows:
Most of this information should be fairly self-explanatory. The Plugin URI is where you can provide a page about the plugin, like your home page, or a blog post specific to the plugin. For the version, start out with something like 0.1 while you’re still developing it (you can then advance to 1.0 once it’s complete). In order to be accepted into the WordPress directory, plugins must be GPLv2 compatible, so unless you have reason otherwise, leave the license as GPL2.
It is then customary, though not required, to follow your header with license information. Paste the following if you’re using GPLv2 and change the first line to reflect your own information:
Creating the widget
Now you’re ready to start adding some code to your plugin. Consider the unique name you came up with earlier for your plugin folder name. Now use that to create your widget class, replacing any hyphens with underscores and tacking _widget on the end. So for example, the start of my plugin file looks like this:
I’ve used soup_widget for my widget class. Everytime you see soup_widget in your code, replace it with your own widget class. Replace my widget description with your own short description and in line 10, replace ‘Upcoming’ with a title that will appear in your widget screen (see picture for example).
Now, we’re going to create arguments for you to use in your code. These are going to depend on the variables we came up with earlier when considering what information we needed to collect (title, soup_number, newsletter_url etc.):
The way they will appear will depend on how you’re going to collect the information. Leave the title as it is, but for text inputs or drop-down menus with preset options, use the format as shown with $soupnumber, $posttype and $newsletterurl. If you’re going to use a checkbox, copy the format of $shownews and $newsletterurl. These are different because the value that will be stored in the database will be either true or false (boolean), whereas the others are just text entries and can have any value.
Incorporating theme support
WordPress provides theme authors with a few functions that allow them to style widgets properly, so we want to include these items so that the theme displays the widget as the author intended. As such, the next block of code will be:
Note that I have left a placeholder for you to put your actual widget code (WIDGET CODE GOES HERE). This is where we code what the widget will actually display when loaded. In my example, I’ll be taking all the options and using them to display upcoming posts and maybe some other parts, depending on whether those options are selected.
The actual widget code
The first section of code in my widget output (lines 1-15) queries the database to find the number and type of posts that the user wants and displays them in a bulleted list. Look at the following and note that I’ve used the arguments $soupnumber and $posttype in my query. Your code may not need to query the database, but this demonstrates the use of arguments in the code and the results they deliver. The part below it (lines 16-21) print a link to the site’s RSS feed and encourages users to sign up so that they don’t miss it. I’ve used the bloginfo function to return the values for the RSS feed and the site’s address. Because my widget displays an image, I’ve used the site address to navigate to the image (/wp-content/plugins/soup-show-off-upcoming-posts/icons/rss.png):
Note that if you want to use HTML, you need to close the PHP tags. To start using PHP again, you need to open the PHP tag back up.
In the next section of code, I’m checking whether or not the option to display the newsletter link is checked; if it is, it will display the link to the newsletter subscription site – if not, it will just skip over it:
That completes the actual code of my widget; it shows the posts, displays a link to the RSS feed, displays a link to the newsletter if needed and optionally gives credit to the author. But we’re not quite done with the plugin – we need to add the control panel that will allow users to input their options and then provide the code that will save those options to the database.
Updating options in the database
This next section of code takes any new options that are entered in the widget control panel and commits them to the database. All you need to do is add new lines for each option you have:
You’ll notice that the title and soup_number are stripped of any PHP or HTML tags to stop people from incorrectly trying to add code where they shouldn’t. The newsletter_url is only allowed ‘a’ tags.
Set up the widget control panel
The last major component of your widget code is the code that will create the control panel. This control panel is where the user enters all of their options and they can be committed to the database.
It’s essentially an HTML form which can include drop down menus with multiple options, checkboxes and text entries among other input fields. I have examples of all three in the SOUP widget, so just copy the format to create as many as you like.
Before you actually display the form, you can (not required) create some defaults for the options. For example, as you will see in my code, the default widget title is ‘Upcoming Posts’ and the default number of posts to show is 3, but the newsletter_url does not have a default:
Use this as a template for adding drop-down menus, checkboxes and text entries. Merely change the variables, labels and options in each case.
Now you’re ready to register the widget. Just add the following after the control panel code and change out soup_widget for your own unique widget class:
Now that you’re done with all of that, your file should look something like this:
Installation and testing
Now save the file and head to the plugins section of your WordPress site, where you should see your plugin awaiting activation. Go ahead and activate it.
With any luck, you’ll get a message saying that your plugin was activated. If you get a fatal error, you’ve probably got a clashing function name and you’ll want to make your function more unique.
Then if you head to your Widgets (Appearance > Widgets), you should see your widget waiting to be installed. Try installing it in a sidebar and see how it looks. Try entering data and saving it. Check that it gets reflected in your widget. Test all scenarios (no data, bad data, good data) to see how your widget reacts.
Once you’ve ironed out all the kinks, you’re probably ready to submit it to the WordPress directory. After all, if you needed it, the chances are that someone else does!