Change widget's CSS class names for different category pages in WordPress

半城伤御伤魂 提交于 2019-12-12 04:07:27

问题


I want to change the class names of the sidebar widgets on every different category page of WordPress and I figured the best way to do this would be to make a function in functions.php with all the conditions and return the required class name. I then called the function in the list tags of the register_sidebar function.

if (function_exists('register_sidebar')) {
  register_sidebar(array(
   'before_widget' => '<li class="sidebarModule">',
   'after_widget' => '</li><!-- end module -->',
   'before_title' => '<h2 class="moduleTitle "'.set_widget_title_color().'>',
   'after_title' => '</h2>',
  ));
}


function set_widget_title_color() {

    if(is_category('technology')) {
        $color = "catNavColor1_active";
    } elseif(is_category('gadgets')) {
        $color = "catNavColor2_active";
    } elseif(is_category('social-media')) {
        $color = "catNavColor3_active";
    } elseif(is_category('gaming')) {
        $color = "catNavColor4_active";
    } elseif(is_category('other')) {
        $color = "catNavColor5_active";
    }

    return $color;
}

For some reason the above doesn't work. Please Help

Thanks


回答1:


I think register_sidebars is called too early in the process, when the category is not defined yet. Have you tried implementing the dynamic_sidebar_params filter? I could not find anything in the WordPress Codex, but I found this nice example. Your other question on this topic also has a complete answer.

This only works if you implement the sidebars using dynamic_sidebar in your widget, as this function calls the dynamic_sidebar_params filter. If you have static widgets (defined in your template, not using the widget admin page), you should add a call to your function in that template code, like this:

<li class="sidebarModule">
<h2 class="moduleTitle <?php echo set_widget_title_color(); ?>">Widget title</h2>
<?php /* Your widget code */ ?>
</li><!-- end module -->


来源:https://stackoverflow.com/questions/2180689/change-widgets-css-class-names-for-different-category-pages-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!