Skip to content

Instantly share code, notes, and snippets.

@mglaman
Created June 12, 2013 02:10
Show Gist options
  • Save mglaman/5762356 to your computer and use it in GitHub Desktop.
Save mglaman/5762356 to your computer and use it in GitHub Desktop.
Allows the ability to add custom classes to WordPress widgets (just through filter, does not add form.)
<?php
//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