questions

Custom Nav Menu Walker

Rate this post

I am trying to set a WordPress Nav with my own css classes but I am getting compatibility issue again and again I tried to follow the different available results all looks same but I am not sure what causing this issue. Please help me to resolve this

Warning: Declaration of Selective_Walker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = NULL, $id = 0) in functions.php on line 69

Here is my functions.php code

class Selective_Walker extends Walker_Nav_Menu{
    function display_element($element, &$children_elements, $max_depth, $depth=0, $args, &$output)
    {
        $id_field = $this->db_fields['id'];
        if ( is_object( $args[0] ) ) {
            $args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
        }
        return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }

    function start_el( &$output, $item, $depth, $args) {
        if ( $args->has_children ) {
            $item->classes[] = 'submenu';
        }
    }
}

Here is my header.php code where I want to expect the menu

wp_nav_menu( array(
    'theme_location' => 'primary-menu',
    'container' => 'nav',
    'container_class' => '',
    'container_id' => '',
    'menu_class' => '',
    'menu_id' => '',
    'walker' => new Selective_Walker,
    'depth' => 0
    )
);

Expected Menu Structure

<nav>
<ul>
    <li><a href="#">Home</a></li>
    <li class="has_children"><a href="#">About</a>
        <ul class="sub-menu">
            <li><a href="#">Our Mission</a></li>
        </ul>
    </li>
    <li><a href="#">Services</a></li>
    <li class="submenu"><a href="#">Products</a>
        <ul class="children">
            <li><a href="#">Lorem Ipsum</a></li>
            <li><a href="#">Lorem Ipsum</a></li>                
        </ul>
    </li>
    <li><a href="#">Contact Us</a></li>
</ul>
</nav>

 

✔️Solution:

PHP tells you this

Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = NULL, $id = 0)

is not the same as this

Selective_Walker::start_el(&$output, $item, $depth, $args)

So you have to change your start_el method to:

function start_el(&$output, $item, $depth = 0, $args = NULL, $id = 0) {

Why?

Because the base-class (Walker_Nav_Menu) relies on the start_el Method to not change its signature (parameters/data-types/default-values/return-type). If you would be able to overwrite the start_el with a different signature the code of the base-method is very likely to break.

Leave a Reply

Your email address will not be published.

Back to top button