• I am trying to show a custom text in menu. I am using below code on functions.php of current theme.

    add_filter( ‘wp_nav_menu_items’, ‘add_search’, 10, 2 );

    function add_search( $items, $args ) {

    if ( $args->theme_location == ‘primary’ ) {

    return $items . ‘<li>Custom HTML</li>’;

    }

    }

    But I can’t see anything in Menu.

Viewing 5 replies - 1 through 5 (of 5 total)
  • You are making mistake in your code. Use this instead:

    add_filter( 'wp_nav_menu_items', 'add_search', 10, 2 );
    
    function add_search( $items, $args ) {
        if ( $args->theme_location == 'primary' ) {
            $items .= '<li>Custom HTML</li>';
        }
        return $items;
    }
    

    You are welcome ??

    Thread Starter mabufoysal

    (@mabufoysal)

    Thanks @mqasimkh . But I can’t see Custom HTML in Menu. My menu is like below. May be I am doing mistake here .

    $args->theme_location == 'primary'
    enter image description here
    Moderator bcworkz

    (@bcworkz)

    Look at your theme’s call to wp_nav_menu() and see what args it actually passes. Even if the end result is to display the primary menu, it may not be a passed arg. The default value for theme_location is just ''. Your theme could be passing a “menu” arg instead of “theme_location”.

    Thread Starter mabufoysal

    (@mabufoysal)

    Thanks @bcworkz. How to know which wp_nav_menu() is working ? I found lots of wp_nav_menu() in my current theme.

    What should I pass here $args->theme_location == 'primary' ?

    Thanks.

    Moderator bcworkz

    (@bcworkz)

    It’s the wp_nav_menu() call on the template that’s responsible for outputting the menu you’re trying to target. If it’s the main menu that’s within the header part of a page, it’s often the call from header.php template (or a referenced template part) if you use a classic theme.

    Since you’ve not indicated which theme, I cannot even hazard a wild guess. And unless it’s a free and open source theme, I couldn’t say even if I knew your theme. I can say however, that if “theme_location” isn’t working, your theme is most likely passing a “menu” parameter in order to get the right menu. Either way, the solution is to determine how your theme is managing this.

    I can confirm that Muhammad’s suggested code does work on a Twenty Twenty-one theme, so the only reason for failure is a conditional inappropriate for your theme.

    But wait! One other possible reason: caching. The code could be working but you’re seeing stale, cached content. Always try clearing any caches, both client and server side before deciding certain code does not work.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Show a text in menu’ is closed to new replies.