简体   繁体   中英

Custom menu tags in wp_nav_menu

I've been trying to get the function wp_nav_menu() to output the following html structure:

 <ul> <li><a href="#">LINK</a></li><span>element</span> <li><a href="#">LINK</a></li><span>element</span> <li><a href="#">LINK</a></li><!--no element HERE!--> </ul> 

I tried with parameters like 'after' and 'link_after'. But the first one outputs the element before </li> tag and the next one before </a> tag. Is there any way to output the <span> element after </li> tags? I read about the Walker class but I don't quite understand its logic - I'm not that good at PHP.

I have no wp installed to test it, but still leave it here. You need to extend the Walker_Nav_Menu class, like this:

class custom_walker_nav_menu extends Walker_Nav_Menu 
{
    public function end_el( &$output, $item, $depth = 0, $args = array())
    {
        $output .= "</li><span>element</span>\n";
    }
}

And then pass new custom_walker_nav_menu as $walker parameter for wp_nav_menu() function. Actually, this answer is uncomplete, can't get how to get rid off last <span> element you don't need. I'll try to improve it later. Also as @ rnevius mentioned in his comment it would be an invalid HTML, so you should definately use one of after or link_after .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM