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

public function __construct() {
   $widget_ops  = array(
      'classname'                   =>; 'widget_text eaa __eaa__', //__eaa__ is my placeholder css class
      'description'                 =>; __( 'AdSense ads, arbitrary text, HTML or JS.','eaa' ),
      'customize_selective_refresh' =>; true,
   );
   $control_ops = array( 'width' =>; 400, 'height' =>; 350 );
   parent::__construct( 'eaa', __( 'Easy AdSense Ads & Scripts', 'eaa' ), $widget_ops, $control_ops );
}

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

if ( $instance['no_padding'] ) {
   $args['before_widget'] = str_replace( '__eaa__', 'eaa-clean', $args['before_widget'] );
}

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

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