Actually, all I need is to change one specific button in the menu, so
it is different when the user is logged in – in that case that menu
button will be a “Member profile” button instead of a “Log in” button
Yes, you can use only one menu, assuming its slug is ‘my_menu’ do not add to it member profile nor login url, instead use wp_nav_menu_{$menu_slug}_items
filter:
// 'my_menu' in filter name is the slug of the menu
add_filter('wp_nav_menu_my_menu_items', 'menu_add_admin_buttons', 20, 2);
function menu_add_admin_buttons( $items, $args ) {
$btn_format="<li><a href="https://wordpress.stackexchange.com/questions/112324/%s">%s</a></li>";
if ( is_user_logged_in() ) {
$btn = sprintf($btn_format, admin_url('profile.php'), __('Your Profile') );
} else {
$btn = sprintf($btn_format, wp_login_url(), __('Log In') );
}
return $items . $btn;
}
$items
are the current html for the current menu items, a string containg a series of <li><a ... </a></li>
.
The slug of the menu is equal to sanitize_title($menu_name)
i.e. it removes all special chars, converted accented chars with non accented ones and convert spaces to -
.
E.g. if the name is “Main Menu” the slug is “main-menu”.
The name your menu is called is what you write in wp backend when you create menu, see image below.
Of course is possible use sanitize_title
to create the filter dinamically from name, e.g.
$menu_filter="wp_nav_menu_" . sanitize_title("Main Menu") . '_items';
add_filter($menu_filter, 'menu_add_admin_buttons', 20, 2);