|

WordPress Widgets Tutorial

wordpress widget

WordPress Widgets are a cornerstone of WordPress theme development and in this tutorial we will explore them in depth. So what is a WordPress Widget? A Widget in WordPress is a way to group together a chunk of content that is specific to a given purpose, and then displayed on the website. If you visit Appearance and then Widgets in the WordPress dashboard, you will see many types of widgets available to use. Common widgets you may see on a website include an Archives widget, Calendar Widget, Latest Blog Posts Widget, Latest Comments Widget, and many more. Let’s take a closer look at Widgets now, and how we can incorporate them into the custom theme that we have been building together.


Making Space For Widgets

Before you can add any widgets to your theme, you need to make some space available for them. For example, you might like to make use of a widget in a sidebar area, or in the header area, or perhaps in the footer area of your theme. First up, we’ll see how to make use of div elements and css to create a two column theme from scratch so that we can start adding widgets. We are going to need a div that we float to the left for our main content, and a div that we will float to the right for our sidebar area where we will place a widget. We can start by modifying our index.php file and adding some custom css to our style.css in order to make the layout work.

index.php

style.css

Ok let’s talk about this for a moment. The first thing we will notice is that in WordPress theme files there will be a lot of mixing PHP code into HTML layout markup. This is a source of frustration for some, and will likely be for you at times, but this is how things are done in WordPress and unfortunately we will not always have a 100% separation of concerns. There will be times when you have to drop out of PHP and then reopen PHP by using a closing tag such as ?> and then a reopening PHP tag such as <?php. In between the closing and opening PHP tags, you can write plain old HTML markup. You may already be quite familiar with this, but it is something to be aware of nonetheless. Now, another thing you will notice is that we make use of HTML comments in the index.php file. This is to help us keep track of opening and closing div elements. With no comments, you will likely end up with situations where you don’t no what closing div corresponds to what opening div. We used comments of <!– main-content –>, <!– main-column –>, and <!– sidebar-column –> to help us in this respect.

Now the actual markup contains 3 divs. The outermost div is a wrapper of sorts, and gives us a way to manage the two columns it contains. Inside that parent div are two child divs. One is floated to the left with a 70% width, and the other is floated to the right with a 30% width. Note that the parent div needs the css property of overflow: auto in order for this all to work properly. Otherwise, the parent div will not automatically expand, or grow it’s height, to contain the two child divs. Don’t you just love CSS?!

Let’s visit the website to see how things are coming along. Our two column layout is now in place.
two column layout wordpress


Adding A Dynamic Widget Location

Anytime you want to enable a feature or register something to become active in WordPress you will likely be adding something to or refactoring something in the functions.php file of your WordPress theme and it is no different when turning on Dynamic Widgets in your WordPress theme. So let’s go ahead and open up that functions.php file now and add some widget locations.

Before we ‘turn on’ Widgets in our WordPress theme, let’s just prove to ourselves that they are not available just yet. If we navigate to the Dashboard and hover over appearance, we can see that there is not yet a sub menu of Widgets. We can change that now!
no widgets available yet

Pay attention to the highlighted code at the end where we turn on Widget support in our WordPress theme. Note that it is the register_sidebar() function that is doing the heavy lifting for us here.
functions.php

With this in place, let us re visit that admin dashboard. Check it out!
widgets are now available

Let’s review how this works. What we did was to create our very own function named initialize_widgets(). Inside of this function, we make a call to the register_sidebar() function offered by WordPress. Now, it’s a bit of an oddly named function because it is actually quite flexible. What we are really doing here is registering a widget location. It could be in the sidebar, header, footer, or anywhere else that we like. Now in terms of what we pass as an argument to the register_sidebar() function, you will notice that we are passing in an associative array which contains two key and value pairs. The first key is that of ‘name’ which has a value of ‘Right Sidebar’. This refers to the human readable display that shows up in the WordPress Widgets area. The second key is ‘id’ with a value of ‘rightsidebar’. This value will never be seen by the user or in the WordPress dashboard area. It is there for WordPress to uniquely identify one widget area vs another.

When we visit http://wordpresstutorial.dev/wp-admin/widgets.php in the WordPress Dashboard, we can see very clearly our new Widget Location has been enabled. Very nice!
naming widget locations


How To Use dynamic_sidebar() in your theme

We are at the point now where we have used HTML and CSS to set up a two column layout, and turned on Widget Locations via our functions.php file. You might be tempted to drag one of those widgets from the WordPress dashboard right into that ‘Right Sidebar’ we have created. You could do that, but it would not work yet. We still need the help of the dynamic_sidebar() function to make this work. Now, recall that when we had made use of the register_sidebar(), there was an ‘id’ associated with a particular sidebar location. We will need to pass the value of that id into our dynamic_sidebar() function in order to activate the widget. Let’s see how to do this right here.

index.php

With this portion of code in place, let’s go ahead and drag a widget into our right sidebar area in the WordPress Dashboard.
drag available widget to widget location

Let’s now visit the main website and notice that our sidebar does have the list of categories with links. So this Widget is now working!
category widget is now working

We can now add any of the following Widgets to our sidebar if we like.

  • Archives
    A monthly archive of your site’s Posts.
  • Audio
    Displays an audio player.
  • Calendar
    A calendar of your site’s Posts.
  • Categories
    A list or dropdown of categories.
  • Custom Menu
    Add a custom menu to your sidebar.
  • Image
    Displays an image.
  • Meta
    Login, RSS, & WordPress.org links.
  • Pages
    A list of your site’s Pages.
  • Recent Comments
    Your site’s most recent comments.
  • Recent Posts
    Your site’s most recent Posts.
  • RSS
    Entries from any RSS or Atom feed.
  • Search
    A search form for your site.
  • Tag Cloud
    A cloud of your most used tags.
  • Text
    Arbitrary text or HTML.
  • Video
    Displays a video from the media library or from YouTube, Vimeo, or another provider.

How To Add A Widget To The WordPress Footer

You can put Widget locations where ever you might like in your themes. Just to show how this works, let’s now go ahead and add a Widget to the footer area of our website. So how do we do this? First we again register a widget location in functions.php, then we add the code to footer.php that will output a dynamic widget, and lastly we of course drag one of the available widgets into our newly created widget location. Let’s try it out!

Previously we had set up the initialize_widgets() function in our functions.php file. Inside of that function, we made a call to register_sidebar() to set up a widget location. Well, we want to add another widget location, this time in the footer, so we need to make another call to register_sidebar() but this time notice we pass in a different value for ‘name’ and also a different value for ‘id’. The name of ‘Footer’ is what the user will see in the WordPress dashboard widget area while the id of ‘footer’ is what we will pass into the dynamic_sidebar() function in our footer.php file. Makes sense, right?!

We can now drag another Widget into the Footer location in the Dashboard as we see here. This time around we will select the Pages widget to display in the footer.
footer location widget settings

Let’s update that footer.php file so that we will see the output of our new widget.
footer.php

We now have an active widget in the footer of our site and it is giving us a nice display of the pages in our website in a nice list format. We haven’t done any styling yet so our widgets look a little bland, but we got them working and that is the fun part.
widget in footer of wordpress site


Checking for active widgets with is_active_sidebar()

Now we will add a bit of a best practice piece of logic to our code. When we output widget markup with the dynamic_sidebar(), and also any wrapping divs that are preset, we should first check to see if a particular widget location is even active. We can do this with the is_active_sidebar() function. What this function does is to check if the user has even configured a widget for a specific widget area. Only if the widget has been set up and configured in the WordPress dashboard should we output it in the html of the page. You need to pass in the id of the widget you are checking when calling the is_active_sidebar() function. Let’s see how to add this logic to our two widget locations.

Using is_active_sidebar() in index.php

Using is_active_sidebar() in footer.php


How to change the outer

  • tag on a WordPress Widget
  • You might have noticed something a bit odd about the output of the widgets on our website. The title of the widget has a bullet point as if it is part of a list, but really that is not ideal. First, let’s look at the actual markup that WordPress generates when it creates html for the browser to render. Here is the html that was created for our sidebar widget:

    Because the entire <ul> is itself enclosed in an <li> tag, it looks a little funny on the page. We can fix this by passing some additional arguments to the register_sidebar() function in our functions.php file. Specifically, we want to specify the ‘before_widget’ and ‘after_widget’ options. Here is how we can do that to customize the output of the html for WordPress Widgets. We can update the initialize_widgets() function to this code here:

    When we view our widgets on the site, they now do not have that bullet point next to the title of the widget. This looks much better.

    Sidebar Widget
    widget sidebar custom wrapping html
    Footer Widget
    footer widget with custom wrapping html

    Inspecting the actual markup on the page shows us that the widget is no longer using a wrapping li tag, but a div tag.

    The same is also true for the html output of the widget in the footer.


    WordPress Widgets Tutorial Summary

    In this tutorial, we learned all about what is meant by Widgets in WordPress. We learned that they are a self contained block of content that is dynamically added to a WordPress website in widget locations of the theme developer’s choosing. We saw that it is pretty straight forward to add support for Widgets to a custom WordPress theme. We learned that in order to use Widgets in WordPress, we must first use the register_sidebar() function one or more times in functions.php to set up Widget locations. We then need to make use of the is_active_sidebar() and dynamic_sidebar() functions in our theme files to actually output the widget markup to the browser. Lastly, you of course need to drag and drop the widgets you want to activate in the WordPress dashboard and configure the settings to your liking. You now have all the tools you need to make awesome use of Widgets in your own WordPress powered website!