WordPress functions.php Problem

2019-09-01 02:11发布

Can a function inside the functions.php file call another function from within functions.php? I'm guessing yes and which is why I wrote the code below, but it doesn't work for some reason. Can anyone please check it out and help me.

I tried calling pageBarColor() from register_sidebar()

Thanks.

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

function pageBarColor(){
    if(is_category('3')) {
        return "color1";
    } elseif(is_category('4')) {
        return "color2";
    } elseif(is_category('5')) {
        return "color3";
    } elseif(is_category('6')) {
        return "color4";
    } elseif(is_category('7')) {
        return "color5";
    }
}
?>

1条回答
来,给爷笑一个
2楼-- · 2019-09-01 02:41

The problem is probably that when you call register_sidebar Wordpress has not yet executed the code which determines the result of is_category. If you try calling your pageBarColor function straight after defining it you'll find it doesn't return anything. One way of working around this would be to hook into the dynamic_sidebar_params filter (which is called when you call dynamic_sidebar in your templates, assuming you do) and update your widget before_title values, something like this:

function set_widget_title_color($widgets) {
    foreach($widgets as $key => $widget) {
        if (isset($widget["before_title"])) {
            if(is_category('3')) {
                $color = "color1";
            } elseif(is_category('4')) {
                $color = "color2";
            } elseif(is_category('5')) {
                $color = "color3";
            } elseif(is_category('6')) {
                $color = "color4";
            } elseif(is_category('7')) {
                $color = "color5";
            }

            if (isset($color)) $widgets[$key]["before_title"] = str_replace("moduleTitle", "moduleTitle ".$color, $widget["before_title"]);
        }
    }
    return $widgets;
}
add_filter('dynamic_sidebar_params', 'set_widget_title_color');
查看更多
登录 后发表回答