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 01 Answer
Reset to default 1You 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
版权声明:本文标题:php - Show a text in menu 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311067a1934604.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论