Wordpress - maintain the “active” class in the parent menu item

I am using a theme in Wordpress. This topic has a main navigation menu with horizontal submenus under each parent element. It places the "active" class in the current parent elements that are currently being viewed (otherwise, it will not show child elements for children). I managed to somehow save the "active" class in the current parent elements using these two functions in 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 );
    }
}

, - , , "" ( ). , , , ( ) , .

.

+4
2

, , , , - -.. , , - .

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

, , :)

+9

- , , WordPress :

, , current-menu-parent current-page-parent current_page_parent current_page_ancestor, WordPress, , .

0

All Articles