admin管理员组

文章数量:1122832

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.

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.

Share Improve this question asked Apr 9, 2024 at 9:34 FoysalFoysal 4451 gold badge5 silver badges15 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1

You used the correct filter, but the reason it isn't showing has nothing to do with menus, and everything to do with the basics of how filters work.

That filter gives a string and expects a string in return, so if we add type hints the problem becomes much more obvious:

function add_search( string $items, $args ) : string {

Now your site would crash for the same reason your menus are blank:

function add_search( $items, $args ) {

    if ( $args->theme_location == 'primary' ) {
        return $items . '<li>Custom HTML</li>';
    }

    // ---> but what if it is not primary?!!!!!!! <---
}

WP is passing $items giving you an opportunity to modify it, and it needs you to pass it back, you're just borrowing the value so you can filter it.

Because you only return the value when the theme location is primary, PHP doesn't know what to do and assumes you meant null, giving you a null/empty menu. If you do not return then PHP will add return null or an equivalent for you.

Keep an eye on your PHP error log and you'll see code like this generating PHP warnings and notices. These are big clues for security issues and errors in a site

本文标签: phpShow a text in menu