Archived topic
Php to change the text of one menu
6 replies · Started by Randy on October 6, 2021
Hello,
I was trying to figure out what php hook I could use to change the text of one menu item. I will be doing it based on is_user_logged_in() but am not sure how to target the particular menu item (by id, class, text, whatever is easiest)
Thanks!
Hi there,
Using a simple plugin might be the easiest solution:
https://generatepress.com/forums/topic/loginout-and-register-links-in-submenu/#post-1949917
Hope this helps :)
Thanks Leo, I'd rather use a php filter to take care of this. Any thoughts on which one it would be?
The other option I guess would be if there's a way to make one menu item only show for logged out users and another menu item only show for logged in users. Is that something easy to configure in GP?
Hi there,
thats a WP core thing, you can make those kinds of changes using wp_nav_menu_items hook:
https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
Here's a simple example:
function db_custom_logged_out_menu_label( $items, $args ) {
if ( ! is_user_logged_in() ) {
$items = str_replace( "your label", "your logged out label", $items );
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'db_custom_logged_out_menu_label', 9999, 2 );
This will look for a menu nav label of your label and swap it for your logged out label
Excellent David! I will try that.
I had come up with the following (testing with Help menu), which was saying that it changed the title in the error log, but didn't actually change the menu title in the browser...strange:
add_filter( 'wp_nav_menu_objects', function ( $items, $args ) {
foreach ( $items as $k => $object ) {
if ( 4815 == $object->ID ) {
error_log('ORIG MENU TITLE IS' . $object->title);
$object->title = 'HelpTest';
error_log('NEW MENU TITLE IS' . $object->title);
}
}
return $items;
}, 9999, 2 );
error log shows: "PHP message: ORIG MENU TITLE ISHelpPHP message: NEW MENU TITLE ISHelpTest"
Out of curiosity, any idea why the above wasn't actually changing the menu text?
Either way, I'll try the code you suggested :)
Thanks again!
Actually, both codes worked...must have been a caching thing :)
But I'll probably use you code as I'm guessing its more performant since it doesn't have to do a big loop like mine :)
Thanks again David
Glad to be of help!