You can add this code to your active theme’s functions.php file. I would recommend you to use Child theme. The code checks if the user is logged in or not and if the current menu is the primary menu. Then, it adds the appropriate login or logout link to the menu items. The wp_login_url()
and wp_logout_url()
functions generate the URLs for the login and logout pages respectively. The __()
function is used for translation purposes. You can modify the code to match your specific theme and menu requirements.
function add_login_logout_link_to_menu( $items, $args ) {
if (is_user_logged_in() && $args->theme_location == 'primary') {
$items .= '<li><a href="'. wp_logout_url() .'">'. __("Logout") .'</a></li>';
} elseif (!is_user_logged_in() && $args->theme_location == 'primary') {
$items .= '<li><a href="'. wp_login_url() .'">'. __("Login") .'</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_login_logout_link_to_menu', 10, 2 );
16 thoughts on “How to add custom login and logout links in the wordpress navigation or menu programmatically ?”
Good advice! Many thanks!
Really fantastic, this! I really appreciate you sharing this article.
Thanks @Leo Edward
Good advice! Many thanks!
Really fantastic, this! I really appreciate you sharing this article.
Thanks @Leo Edward
It is very simple to add an item, I’ve spend many hours (and not suceeded) working out how to make that show a submenu
Hey, to show a submenu, we need to alter the function. You can reach out to me directly amrinder146@gmail.com. I can sort this out and build for you in 24 hours.
Thanks, Well I’ve finally managed it but it wasn’t simple possibly because I did use the function… I couldn’t find any examples. If you want to add it on your blog that would be great, otherwise I now have something that works.
okay Perfect. Yes, share the snippet on my above mentioned email.
Just sent
Yes, received. Thanks
It is very simple to add an item, I’ve spend many hours (and not suceeded) working out how to make that show a submenu
Hey, to show a submenu, we need to alter the function. You can reach out to me directly amrinder146@gmail.com. I can sort this out and build for you in 24 hours.
Thanks, Well I’ve finally managed it but it wasn’t simple possibly because I did use the function… I couldn’t find any examples. If you want to add it on your blog that would be great, otherwise I now have something that works.
okay Perfect. Yes, share the snippet on my above mentioned email.
Just sent
Yes, received. Thanks