I have created my custom menu having many items and sub items, the markup is like this <a href="#">Item</a>but for parent element I need to replace anchor tag with the span tag having some class for styling purpose, only for my parent elements. It should be like this, <span class="my-class">Parent Element</span>. Can any one please guide me?


The following code added to your themes functions.php will do what you want.

add_filter( 'walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4 );
function my_walker_nav_menu_start_el( $item_output, $item, $depth, $args ) {
    if ( empty( $item->url ) || '#' === $item->url ) {
        $item_output = $args->before;
        $item_output .= '<span class="my-class">';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= '</span>';
        $item_output .= $args->after;
    return $item_output;

This should find all menu items with no URL or # as the URL and replace the link with <span class="my-class">...</span>.

This wouldn't specifically apply to parent menu items, but as long as you use a custom link and don't enter a URL (or you enter a #) for your parent menu items then it should work for you.

  • how to change this code that replace a to span for elements who has sub menu? – voronovam Jul 6 '17 at 2:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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