Skip to content
Advertisement

Print WordPress menu in a tag

I have some WordPress nav menus and I want to print each nav menu under an <a> tag. I tried the following code:

<?php
    wp_nav_menu(
        array(
            'menu'           => 'Main Menu',
            'theme_location' => 'api-footer-main',
            'menu_class'     => 'hex__footer_link', 
            'container'      => 'a',
        )
    );
?>

Tried to use <a> as the container, but that’s printing:

<ul>
    <li><a>Menu</a></li>
    <li><a>Menu</a></li>
    <li><a>Menu</a></li>
</ul>

I want to remove that entire <ul><li> structure. My menu should be printed as:

<a>Menu</a>
<a>Menu</a>

I’ve also tried the following, which removes the <ul> tag, but <li> is still there:

<?php
function wp_nav_menu_no_ul() {
    $options = array(
        'echo'           => false,
        'container'      => false,
        'theme_location' => 'api-footer-main',
        'fallback_cb'    => 'fall_back_menu'
    );
    
    $menu = wp_nav_menu( $options );
    echo preg_replace( array(
        '#^<ul[^>]*>^<li[^>]*>#',
        '#</li></ul>$#'
    ), '', $menu );
}

function fall_back_menu() {
    return;
}

And I’m calling that using <?php wp_nav_menu_no_ul(); ?>

How can I achieve this?

Advertisement

Answer

You might try to use the strip_tags php function, for example:

$options = array(
        'echo' => false,
        'container' => false,
        'theme_location' => 'api-footer-main',
        'fallback_cb'=> 'fall_back_menu'
    );
echo strip_tags(wp_nav_menu( $options ), '<a>' );

See here

For adding the class add the code below in function.php:

function add_menuclass($ulclass) {
   return preg_replace('/<a /', '<a class="some-class"', $ulclass);
}
add_filter('wp_nav_menu','add_menuclass');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement