Adding dynamic classes to your custom WordPress widgets







I recently released an ad management plugin for WordPress called “Easy AdSense Ads & Scripts Manager“.

In this plugin we have a custom widget with option to remove the padding and borders (if any) added by the theme. I did not think much before implementing this feature and was expecting WordPress to have some kind of hook or filter to easily add a class to the widget wrapper and use it to remove the padding and border.

Option that lets you remove padding and borders from the widget

Unfortunately for some reason there is no easy hook or filter in this case. Very strange for WordPress.

But luckily there are two things available

  1. You can add any custom classes to your widget.
  2. There is $args['before_widget']

So here is what I did, use option one to add a custom class, which is actually a place holder which I would replace later. Like this

Now whenever the user checks the remove padding and border option,

I would simply replace this __eaa__ with the class eaa-clean like like below

I could have done this directly skipping the first step of adding a placeholder and directly using a regular expression on $args['before_widget'], but did not for the following reasons.

  1. It did not seem solid, and might fail in some cases.
  2. Since this a plugin that can be used in conjunction with any theme, I don’t have control over what $args['before_widget'] is going to be.

Complete implementation of this can be found on git

Leave a Reply