I've been writing up a function to assign classes to default WordPress widgets that I choose. After a bunch of research and modifications, I came up with the function below.
A quick explanation of what it does:
The variable,
$classes
, holds the class name I want to assign each type of widget to and each widget being assigned a class (ex. I want to add.main-blocks
to the Archives and categories widget).I use an
if
statement to match the widget types to assure that a class is only assigned to a widget I've listed in$classes
. And because each widget gets a unique ID number as well, I've added$widget_num
to check that too. For example, a category widget's HTML may get output like so:<li id="categories-2">...</li>
The problem: I'm thinking I'm not accessing the array
properly, as this code doesn't do anything. I had a version of this working before using a few if/else
statements (just to get things rolling), but I'm more about efficiency than just creating things to work.
When this works, the HTML of the widget should be like this, with classes assigned to my specified widgets:
https://i.stack.imgur.com/hFPI7.png
Thanks for the help!
function md_widget_classes($params) {
global $wp_registered_widgets;
$widget_id = $params[0]['widget_id'];
$widget_obj = $wp_registered_widgets[$widget_id];
$widget_num = $widget_obj['params'][0]['number'];
$classes = array(
'mini-blocks' => array('categories', 'archives'),
'full-blocks' => array('recent-comments', 'recent-posts'),
'blocks-list' => array('links', 'meta'));
foreach($classes as $class => $widgets)
foreach($widgets as $widget)
if($params[0]['widget_id'] == "$widget-$widget_num")
$params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']);
return $params;
}
add_filter('dynamic_sidebar_params', 'md_widget_classes');