assuming you know your css –
you could add (conditionally for single post only) post_class()
to the sidebar template; archives would probably have the category information in the body_class()
.
or try this filter function in functions.php of your theme:
(based on an original post by @mathsmath: https://www.ads-software.com/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets?replies=9 )
function add_before_widget_title_extra_classes($params) {
//* adapted from a code by @MathSmath / found in:
//* https://www.ads-software.com/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets?replies=9
$this_id = $params[0]['id']; // Get the id for the current sidebar we're processing
$arr_registered_widgets = wp_get_sidebars_widgets(); // Get an array of ALL registered widgets
if(!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id])) { // Check if the current sidebar has no widgets
return $params; // No widgets in this sidebar... bail early.
}
if( is_single() ) : global $post; $class = 'class="'; foreach( get_the_category($post->ID) as $pcat ) { $class .= 'category-' . $pcat->slug . ' '; } // Add a widget category class for additional styling options
elseif( is_category() ) : $cat = get_query_var('cat'); $class = 'class="category-' . get_category($cat)->slug . ' '; // Add a widget category class for additional styling options
endif;
if( is_single() || is_category() ) :
$params[0]['before_title'] = preg_replace('/class=\"/', "$class", $params[0]['before_title'], 1); endif;
return $params;
}
add_filter('dynamic_sidebar_params','add_before_widget_title_extra_classes');
(not widely tested)