How To Add Icons To Widget Headers

Working on a current site required me to enter icons before the widget title in a sidebar.

I knew that WordPress wouldn’t allow such detail, and I didn’t want to have to find another plugin to do what I thought would be a menial task… so by resorting to jQuery it ended up being quite easy to do.

The result was to try to achieve something like this:

Widget with corresponding icon displayed

And the way I was able to get this to operate was by using this code:

(function($) {
// move icons in sidebar to be in front of their header
if ( $('#sidebar').length > 0 ) {
// get all widget titles and loop through each
$("#sidebar h4.widget-title").each( function(index) {
// get the sibling textwidget > span
var sibling = $(this).parent().find(".icon-widget");
$(this).before( sibling );
view raw addWidgetIcons.js hosted with ❤ by GitHub

It assumes within the text/html widget you have already defined the icon element in the body of the widget.

For example:

Title: My Widget Title
Body: <span class="icon-phone"></span>
Remainder of your content to go here.

The CSS of the above would be:

.icon-widget {
margin-right: 5px;
.icon-phone {
width: 10px;
height: 10px;
background-image: url("/wp-content/uploads/2013/08/icon-phone.png");
background-size: 100%;
background-repeat: no-repeat;
display: inline-block;