One of my earliest pet-peeves about WordPress was how widgets get their HTML. In core WordPress, a sidebar controls the template for a widget, and that template is set during the registration of the sidebar.

register_sidebar(array( 
	// ...
	'before_widget' => '<div id="%1$s" class="widget %2$s">',
	'after_widget'  => '</div>',
	'before_title'  => '<h2 class="widgettitle">',
	'after_title'   => '</h2>'
));

That approach is not only clunky for new developers to grasp, but lacks any sense of flexibility or extensibility. Consider a very simple use-case: You need a widget to appear in that same sidebar but with some additional classes on the wrapper.

I originally solved this pet peeve in my plugin Widget Wrangler, but that plugin contains a completely new approach to widgets. Sometimes you just want to template widgets in a reasonable way and move on.

Introducing Sweet Widget Templates, a plugin that does just (and only) that: provide a simple, yet powerful, template system for WordPress widgets.

Here is how you would use it:

  1. Download and activate the plugin.
  2. Create a folder within your theme named widgets.
  3. Within that folder, create a new file named widget--default.php.
  4. Copy the Widget Template Example from the plugin’s README into that new file, and modify it to fit your needs.

Using the template suggestions pattern, you can provide templates per-sidebar, per-widget, and per-widget-per-sidebar. Here is a list of the template suggestion patterns:

- {custom-template-name}.php    | If a widget has a specified template name in the Admin Dashboard, that template name takes priority.
- {sidebar-id}--{widget-id}.php | Specific widget in specific sidebar
- {sidebar-id}--default.php     | Any widget in specific sidebar
- {widget-id}.php               | Specific widget in any sidebar
- widget--default.php           | Default template for all widgets in all sidebars

But wait, there’s more! Once the plugin is installed, each widget can now be assigned a template within the Widget UI.

sweet-widget-templates

This means you can create arbitrary widget templates in your theme and assign those templates as needed to individual widgets, regardless of what sidebar in which they may be displayed.

Voila! You now have full control over your widget templates.

Interested in WordPress widgets? Let me know what you think!

About the Author

Jonathan Daggerhart

Long time Drupal and WordPress developer. I like to write modules and plugins, and I dabble in frontend and design.

Leave a Reply

Your email address will not be published. Required fields are marked *