您声明了相同的函数名,这就是“声明的错误”的原因。只需更改类函数(包括在过滤器挂钩中)。或者您可以扩展您的函数代码。我还将重写if结构,使其更易于阅读:
add_filter( \'nav_menu_css_class\', \'add_custom_class\', 10, 2 );
function add_custom_class( $classes = array(), $menu_item = false ) {
//Check if already have the class
if (! in_array( \'current-menu-item\', $classes ) ) {
//Check if it\'s the ID we\'re looking for
if ( 1633 == $menu_item->ID ) {
//Check if is in a single post
if ( is_single() ) {
//Check if the single post is in the category
if ( in_category( \'Services\' ) ) {
$classes[] = \'current-menu-item\';
}
}
} elseif ( 1634 == $menu_item->ID ) {
//Check if is in a single post
if ( is_single() ) {
//Check if the single post is in the category
if ( in_category( \'Products\' ) ) {
$classes[] = \'current-menu-item\';
}
}
}
}
return $classes;
}
此外,此代码几乎是非动态的,因为必须指定菜单ID和类别名称。如果我理解了你的菜单逻辑,那么你是在试图将“当前菜单项”添加到一个类别菜单中,而一篇文章有这个类别。我会编写类似的代码:(因此它适用于任何类别和帖子组合):
add_filter( \'nav_menu_css_class\', \'add_custom_class\', 10, 2 );
function add_custom_class( $classes = array(), $menu_item = false ) {
//Check if already have the class
if (! in_array( \'current-menu-item\', $classes ) ) {
//Check if it\'s a category
if ( \'category\' == $menu_item->object ) {
//Check if the post is in the category
if ( in_category( $menu_item->ID ) ) {
$classes[] = \'current-menu-item\';
}
}
}
return $classes;
}