Support » Themes and Templates » Sidebar widget title colors using post class

  • Im trying to set the sidebar widget title color according to what category the post or archive is in.

    Im using post_class and in my css for eg. .category-name {color:#333;}

    When I register a new sidebar I cannot add <?php post_class ?> to my functions file for 'before_title' =>

    What options do I have to set the color of the widget title?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Michael


    Forum Moderator

    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: )

    function add_before_widget_title_extra_classes($params) {
    //* adapted from a code by  @MathSmath / found in:
    	$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
    	if( is_single() || is_category() ) :
    $params[0]['before_title'] = preg_replace('/class=\"/', "$class", $params[0]['before_title'], 1); endif;
    	return $params;

    (not widely tested)

    Thanks the code works 🙂

    Is there a way to set it so that it gets all the children of the parent category?
    So I only need to set the colours for the parent categories in css. I tried in_category()

    I appreciate you help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sidebar widget title colors using post class’ is closed to new replies.