- This topic has 6 replies, 3 voices, and was last updated 4 years, 6 months ago by
David.
-
AuthorPosts
-
October 6, 2021 at 3:22 pm #1955292
Randy
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!
October 6, 2021 at 3:31 pm #1955297Leo
StaffCustomer SupportHi there,
Using a simple plugin might be the easiest solution:
https://generatepress.com/forums/topic/loginout-and-register-links-in-submenu/#post-1949917Hope this helps 🙂
October 7, 2021 at 4:30 am #1955691Randy
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?
October 7, 2021 at 5:31 am #1955745David
StaffCustomer SupportHi there,
thats a WP core thing, you can make those kinds of changes using
wp_nav_menu_itemshook: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 labeland swap it foryour logged out labelOctober 7, 2021 at 5:57 am #1955761Randy
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!October 7, 2021 at 6:03 am #1955770Randy
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
October 7, 2021 at 6:42 am #1955812David
StaffCustomer SupportGlad to be of help!
-
AuthorPosts
- You must be logged in to reply to this topic.