Creating a Featured Content Widget – With its Own Image Uploader
Creating a Featured Content Widget – With its Own Image Uploader
Have you ever wanted to put something in the sidebar of your website that you couldn’t quite get to work with the default widgets or third party plugins?
Widgets are pretty useful things for sharing related content, displaying authors, top content and more, and using the right widgets can make or break a website.
In this article we’ll take a look at how you can use some code to make your own widgets. You’ll need a basic understanding of PHP and HTML at least. If you know some object oriented PHP that will be a plus, but isn’t necessary to understand the process, as I’ll explain along the way.
Let’s get started.
Note: Scroll to the bottom for a fully working plugin using the code in this post!
Learning by example is the most effective method, so let’s set a goal we want to achieve. A featured content widget is be a good place to start. This widget would allow you to specify a title, add some text, an image and a link. This information would be presented in a nice way in the sidebar.
The screenshots below show how this will all look when used in the new default Twenty Fifteen theme:
We’ll build the widget without the image capability first because it’s a bit simpler. Once we’ve figured everything else out we’ll add in the image to make the widget fully functional.
Creating a Plugin
You can add all the code in this article into your theme’s functions.php file but a widget really is something that should reside in a plugin. Creating one is pretty easy so let’s start with that!
First, create a folder in your
wp-content/plugins directory and name it something unique. I’ll be using
Next, create the main plugin file within the folder. This should have the same name as the folder with a PHP extension:
Open the new file and paste the following PHP comment. This is parsed by WordPress and the information within is used in the plugins section to list your plugin.
At this stage you have a fully functioning plugin! It doesn’t do anything but it will be listed in the plugins section and can be activated. Let’s do so now.
If you want to learn more about creating plugins in general, take a look at our plugin development guide.
The Components of a Widget
Creating a WordPress widget takes four steps. We need to initialize and set up the widget, output a form in the backend, add any rules for processing the backend form and, finally, specify how the widget behaves on the front-end. These steps all translate to specific functions. Let’s look at the big picture by drawing up the structure of our code.
Note that we are creating a class extending the
WP_Widget class. If you have no idea what this means, don’t worry, you don’t need to know any object oriented PHP to create a good widget. What you do need to know, though, is how to initialize the class.
You need to hook a function into
widgets_init and from within that function use the
register_widget() function to initialize the widget by passing it the name of your class.
The “mfc” part of my naming scheme refers to “My Featured Content.” This is called function prefixing and serves to create more unique function names to prevent naming collisions between different plugins.
Another tidbit which may help you is what a “method” and a “property” is. Functions contained within a class are referred to as methods. Variables defined within a class are called properties. There is no significant difference but it’s good to know so you don’t get confused by terminology.
The Widget Constructor
__construct() method contains some basic information about the widget. The base class
WP_Widget takes care of the heavy lifting for is. By adding the code below into the constructor, our widget will show up in the widgets section.
The Backend Form
When the user drags our widget into the sidebar they’ll be presented with a form, which is used to populate the front-end display. In our case we need fields for: The title, the description, the link text and link URL. We add the image in later.
The final version of the
form() method is below. It’s quite long but don’t get to scared – I’ll explain everything underneath.
The only reason this is so long is that we have four fields. We begin by determining the value of each field. The
$instance variable contains the values of our fields if they have already been saved. For each field we create a label and a user input element by using the
The reason we need these functions instead of just typing the names and ids ourselves is that there may be multiple instances of the same widget around. WordPress uses some built-in magic to manage all this for us. The final name of our input element may be
widget-mfc_widget[link_url] instead of just
link. This is how WordPress handles multiple widget areas, multiple sidebars and multiple widgets.
The result of this code should be a form in the widgets section you can use to fill out the widget details.
Handling Form Data
update() function we can determine what happens to our form data before it is saved. We actually don’t need anything special so our final function will look like this:
1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts delivered to your inbox - free!
This function is handy if you want to do something to the form data before saving it. A good example is the RSS widget. When you enter the RSS URL and save it, the most recent items are retrieved and cached. You could use the function to validate and sanitize URLs, numbers and other data as well.
Displaying The Widget
widget() function displays our widget. You can add any HTML here and it will be output in the sidebar.
The function takes two arguments: The first one contains data about the widget area itself, and the second contains the instance variables of our widget.
When widget areas are set up a number of parameters are defined. The content to add before/after the widget and before/after the widget title is most prominent. To make sure your widgets play nice with other plugins and WordPress itself it is a good idea to use the following frame when creating plugins:
Into this frame we add the value of the description field and the link, which we construct from the
link_title fields, something like this:
Don’t forget to use string escaping functions, which serve to protect the data before it is served to the user. You can read more about this in the Validating, Sanitizing and Escaping User Data article in the WordPress Codex. The result of our code should be the following:
Adding An Image
We need to enqueue scripts, just like we would do on the front-end or the WordPress admin. The actions to do this must be defined in the constructor function. Let’s add the following to it:
If you’re not familiar with OOP (object oriented PHP) the notation may confuse you here. The second parameter of the
add_action() function is usually a string which indicated the function that is called. The same thing is happening here but we are indicating that we want the
mfc_assets() function from within our class, not the global scope.
The next step is to create the
mfc_assets() function inside our class and enqueue the necessary scripts and styles within it.
Above, we’ve enqueued the
thickbox scripts. These are included within WordPress and are the basic components of the media dialogue. We also include our own
thickbox functionality is also enqueued.
The next step is to modify the backend form to add the image field. We need to figure out the value of the image field and output the controls for it, just like we did before:
Note that this is very similar, the only addition is a button input with the class of
mfc-media-upload.js. The code you will need to paste inside is the following:
This bit of code will open up the media uploader screen when you click the button. Once you’ve chosen an image it will take the URL of the image and put it into the input element so it can be saved. For more information on this read Paul Underwood’s tutorial on adding an image uploader to your plugin.
Finally, we need to use the value of our image field to output an image in the front-end. I added mine above the description like this:
The final result should look something like the screenshot below:
As you can see, creating a plugin takes a bit of work but once you get the hang of it, it should only take 15-20 minutes to churn out a simple one like this. It can add a lot of power and control for a user over a website, not to mention the stress it can take off a developer’s shoulders – the client can manage the sidebar.
If you’d like to see the full code in action you can download the plugin I’ve created for this tutorial. You can activate and use it all you want, make sure to learn something nice from the code!
What uses can you see for this plugin? Is there a way you could use it on your site? Let me know in the comments below.