Skip to main content

Custom WordPress Widget CSS Classes

Published on
One thing that I has always bothered about WordPress widgets is the lack of ability to define custom widget CSS classes for each widget - it is kind of ugly using the stock widget IDs when you have four text widgets. I've been working on a plugin to extend widget functionality to match features found in Drupal's blocks. I just posted a GitHub gist quickly highlighting the WordPress filter hook. I'll get a repo up on GitHub with the full plugin, currently also does widget filtering - or read more for a preview.
//Hook into dynamic_sidebar_params filter
//found in dynamic_siderbar ( wp-include/widgets.php ) line 886
add_filter( 'dynamic_sidebar_params', 'extend_widgets_sidebar_params', 10);
//I have my classes stored within an array in an option called widget_classes
if((!$widget_classes = get_option('widget_classes')) || !is_array($widget_classes) ) $widget_classes = array();
/* Params callback on setting widget params */
function extend_widgets_sidebar_params($params) {
  //Call our globals
  global $widget_classes, $wp_registered_widgets;
$widget_id = $params[0]['widget_id'];
if(!isset($widget_classes[$widget_id]) || $widget_classes[$widget_id] == '')
return $params;

  //The filter is called *after* WordPress sets the before_widget value, so easiest solution to str_replace to add in our classes
$before_widget_string = $params[0]['before_widget'];
$before_widget_replace = 'class="' . $widget_classes[$widget_id] .' ';
$params[0]['before_widget'] = str_replace('class="', $before_widget_replace, $before_widget_string);
return $params;

I'm available for one-on-one consulting calls – click here to book a meeting with me 🗓️