How to add a div to wrap widget content area after widget title

December 14th, 2016 PHP 3,809 views

While developing wordpress theme, it has been always an essential thing for every theme developers. Everytime we create Widgets, wordpress allows us to wrap div to 2 places

  1. Over the whole widget
  2. Over the widget title

but there is no option to wrap a div over the widget content.

Here is the syntax that shows the options of register_sidebar() function.

Here if you notice, before_widget and after_widget are the options to wrap the whole Widget using div. And same way “before_title” and “after_title” are the options to wrap the widget title. But we don’t have any option here to wrap the widget content. So the final generated widget code will be like this.

No doubt, wordpress also adds its own css class names to the Widget wrapper.

widget_search for search widget
widget_categories for categories widget
widget_text for text widget

We can use these class names to target specific widgets and style them.
But not everyone remembers these class names. And what if we installed some plugin for displaying some custom widget? Then it will have it’s own class name too. So the best practice is to add our own class nameed wrappers to

  1. Whole Widget
  2. Widget Title
  3. Widget Content

So here is how we do this. Do a register_sidebar() as below

This works pretty good but when someone adds widget without a Title, it breaks. As “before_title” and “after_title” will not come in action and the end result will look like this.

So there is 2 closing divs which breaks the html structure.

To solve this issue, we have to write a filter. Here is how we do it :

What this code does?

  1. It checks the settings for the registered sidebar for widgets ending in 2 closing divs
  2. It checks if there is no title given
  3. If no title is given, it modifies the before_widget output to show the opening widget content div

And here is finally how it generates the widget when both widget title and widget content are provided.

And when widget title is not provided, it looks like this.

Hope you found this helpful. Please don’t forget to leave your comments and share it with others.

Leave your comments: