Instantly share code, notes, and snippets.

What would you like to do?
Allows the ability to add custom classes to WordPress widgets (just through filter, does not add form.)
//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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment