wordpresswp-nav-walker

Display menu label twice in wp_nav_walker menu WordPress


I want to have two <span> tags inside a WordPress menu as shown in the code below:

<ul>
    <li><a href="#!"><span>Home</span><span>Home</span></a></li>
    <li><a href="#!"><span>About</span><span>About</span></a></li>
    <li><a href="#!"><span>Contact</span><span>Contact</span></a></li>
</ul>

Solution

  • First, you can use Walker. Create new Class and you need a function called start_el (you can find it inside a wp-includes/class-walker-nav-menu.php). Most simple way just to copy it all. You need to change $item_output

    class Your_Walker extends Walker_Nav_Menu {
    public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
    // Code here
            $item_output  = $args->before;
            $item_output .= '<a' . $attributes . '>';
            $item_output .= $args->link_before . $title . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    }
    }
    

    You can mention anchor tag and inside it $title (links title). You can just wrap $title into span and double it, like that:

    class Your_Walker extends Walker_Nav_Menu {
    public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
    // Code here
            $item_output  = $args->before;
            $item_output .= '<a' . $attributes . '>';
            $item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
            $item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    }
    }
    

    Notice $args->link_before/after can be used via calling wp_nav_menu and there is no need to add extra span (I'll explain it bellow).

    Second way: a little bit tricky but simplier and it will work. Call wp_nav_menu like this:

    wp_nav_menu(array(
        'theme_location'    => 'your_location',
        'link_before'       => '<span>', // This will wrap your title
        'link_after'        => '</span>',
     ));
    

    And in your functions.php

    function add_double_span_to_menu( $item_output, $item, $depth, $args ){
        
        // replace closing '</a>' with '<span>Links Title</span></a>'
        $replace = $args->link_before . $item->title . $args->link_after . '</a>';
        $item_output = str_replace('</a>', $replace, $item_output);
    
        return $item_output;
    }
    add_filter('walker_nav_menu_start_el', 'add_double_span_to_menu', 10, 4);