Get menu links only

All we need is an easy explanation of the problem, so here it is.

I’m creating a template in HTML5. On navigatiom menu i need to implement something like this

<nav>
 <a href="url1" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">url1</a>
 <a href="url1" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">url2</a>
 <a href="url1" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">url3</a>
 <a href="url1" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">url4</a>
 ...
 <a href="urln" rel="nofollow noreferrer noopener">urln</a>
</nav>

If i use ‘wp_nav_menu’, it prints

<div><ul><li><a>

when i need just

<a>

There is a way to get that? Thanks!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Use a custom walker:

class WPSE_33175_Simple_Walker extends Walker
{
    public function walk( $elements, $max_depth )
    {
        $list = array ();

        foreach ( $elements as $item )
            $list[] = "<a href='$item->url'>$item->title</a>";

        return join( "\n", $list );
    }
}

… and then call wp_nav_menu() like this:

wp_nav_menu(
    array (
        'theme_location' => 'your_registered_theme_location',
        'walker'         => new WPSE_33175_Simple_Walker,
        'items_wrap'     => '<nav>%3$s</nav>'
    )
);

Method 2

I’d suggest using the wp_nav_menu_items filter.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply