Our Blog

How to add custom login and logout links in the wordpress navigation or menu programmatically ?

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 ?”

  1. 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

      1. 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.

  2. 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

      1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top