2

I want to add "anchor" tag adjacent to every "list item" that has children.

this is my Walker_Nav_Menu class:

class Menu_Walker extends Walker_Nav_Menu {

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

    $ident = str_repeat( "\t", $depth );

    if ( $args->walker->has_children ) {

        $classes = 'menu-item-has-children menu-item menu-item-' . $item->ID;

        // actual link
        $output .= "$ident<li class=\"$classes\"><a href=\"$item->url\">$item->title</a></li>\n";

        // added tag after
        $output .= "<a class=\"added\" href=\"#\">txt</a>";

    } else {

        $classes = 'menu-item menu-item-' . $item->ID;

        // actual link
        $output .= "$ident<li class=\"$classes\"><a href=\"$item->url\">$item->title</a></li>\n";
    }
}

This is the structure of the menu in WordPress:

enter image description here

But the output is not nested correctly as you can see in image below:

enter image description here

Please help me fix this problem

2
  • Of course they’re not nested correctly. You close li tag in your start_el, so how could they be correct ;) Commented Oct 10, 2018 at 6:04
  • 1
    @Krzysiek Dróżdż omg you're correct, I was trying to solve this problem for the last 2 hours, removing the li closing tag solved it thank you so much.
    – Rozo
    Commented Oct 10, 2018 at 6:07

1 Answer 1

2

You have this problem, because of your code ;)

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

    $ident = str_repeat( "\t", $depth );

    if ( $args->walker->has_children ) {

        $classes = 'menu-item-has-children menu-item menu-item-' . $item->ID;

        // actual link
        // you SHOULDN'T close the li tag in here
        $output .= "$ident<li class=\"$classes\"><a href=\"$item->url\">$item->title</a></li>\n";

        // added tag after
        $output .= "<a class=\"added\" href=\"#\">txt</a>";

    } else {

        $classes = 'menu-item menu-item-' . $item->ID;

        // actual link
        // you SHOULDN'T close the li tag in here
        $output .= "$ident<li class=\"$classes\"><a href=\"$item->url\">$item->title</a></li>\n";
    }
}

In your start_el you close the li tag, so children can't be printed inside of it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.