Wordpress - 在父菜单项上维护"活动"类

 Andy 发布于 2023-02-09 22:23

我正在Wordpress中实现一个主题.此主题有一个顶部导航菜单,每个父项下都有水平子菜单.它在当前查看的当前父项上放置一个"活动"类(否则它不会显示它的子子菜单项).我通过在functions.php中使用这两个函数,以某种方式设法在当前父项上维护"活动"类.

/**
 * Wp Nav Menu Customizer.
 */
function special_nav_class($classes, $item){
     if( in_array('current-menu-item', $classes) ){
             $classes[] = 'active ';
     }
     return $classes;
}
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);


class SH_Last_Walker extends Walker_Nav_Menu{

   function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

        $id_field = $this->db_fields['id'];

       //If the current element has children, add class 'sub-menu'
       if( isset($children_elements[$element->$id_field]) ) { 
            $classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'has-sub-menu';
            $element->classes =$classes;
       }
        // We don't want to do anything at the 'top level'.
        if( 0 == $depth )
            return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );

        //Get the siblings of the current element
        $parent_id_field = $this->db_fields['parent'];      
        $parent_id = $element->$parent_id_field;
        $siblings = $children_elements[ $parent_id ] ;

        //No Siblings?? 
        if( ! is_array($siblings) )
            return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );

        //Get the 'last' of the siblings.
        $last_child = array_pop($siblings);
        $id_field = $this->db_fields['id'];

            //If current element is the last of the siblings, add class 'last'
        if( $element->$id_field == $last_child->$id_field ){
            $classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'last';
            $element->classes =$classes;
        }

        return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}

但现在我的问题是,当我点击任何父菜单项的子菜单或子菜单时,它成功将我带到子页面,但从父项中删除"活动"类并将其放在子项上(因为它是当前查看的页面).我不希望它把这个课程放到孩子们身上,我希望每当孩子们被观看时,它都在那里(在父项目上).

任何帮助将非常感激.

1 个回答
  • 如果你想在子菜单项处于活动状态时让下拉宏祖父项处于活动状态,那么你可以检查当前菜单 - 祖先或当前页面 - 祖先..在你的情况下,我认为当前菜单 - 祖先检查是最有利的.

    function special_nav_class($classes, $item){
         if( in_array('current-menu-item', $classes) || in_array('current-menu-ancestor', $classes) ){
                 $classes[] = 'active ';
         }
         return $classes;
    }
    

    我希望这会有所帮助,祝你有愉快的一天:)

    2023-02-09 22:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有