Skip to content

How To Add Login/Logout Links To WordPress Navigation Menu

If you manage a membership based website, then it’s really important to add login/logout links to the navigation menu of your WordPress powered website. Here’s an amazing snippet, which allows you to add login/logout links to WordPress navigation menu, which will only appear to logged in/ logged out users.

Just add the following snippet to your current theme’s functions.php file:

if( ! function_exists( 'add_loginout_to_menu' ) ) {
    function add_loginout_to_menu( $items, $args ){
        //Nav location in your theme. In this case, primary nav. Adjust accordingly.
        if( is_admin() ||  $args->theme_location != 'primary' )
            return $items; 
        if( is_user_logged_in( ) ) {
            $link = '<a href="' . wp_logout_url('/index.php') . '" title="' .  __( 'Logout' ) .'">' . __( 'Logout' ) . '</a>';
        }
    else  $link = '<a href="' . site_url( '/wp-login.php' ) . '" title="' .  __( 'Login' ) .'">' . __( 'Login' ) . '</a>';
        return $items.= '<li id="loginout-link" class="menu-item menu-type-link">'. $link . '</li>';
    }
}
add_filter( 'wp_nav_menu_items', 'add_loginout_to_menu', 10, 2 );

Don’t forget to define the name of your menu in the 4th line of the above snippet. In most cases, such as default WordPress themes, it will be primary, but don’t forget to take a look at your functions.php file to find it out.

Leave a Reply

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