How to Add a Login Link to the WordPress Navigation Menu (wp_nav_menu)

Home » Snippets » How to Add a Login Link to the WordPress Navigation Menu (wp_nav_menu)

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

When building a WordPress site, one of the most common goals is to create a streamlined experience for your users. One way to do this is to add a login link directly to your navigation menu, making it easy for users to access their accounts from anywhere on your site. However, adding a login link to the wp_nav_menu isn’t as straightforward as you might think. In this article, we’ll guide you through the process step-by-step, so you can add a login link to your WordPress navigation menu with ease.

					function wpturbo_add_login_link_to_menu( $items, $args ) {
    if ( $args->theme_location == 'primary' ) { // replace primary with your menu location identifier
        if ( ! is_user_logged_in() ) {
            $items .= '<li class="menu-item">' . wp_loginout( home_url(), false ) . '</li>';
    return $items;
add_filter( 'wp_nav_menu_items', 'wpturbo_add_login_link_to_menu', 10, 2 );

If you’ve ever wanted to add a login link to your WordPress navigation menu, you’ll be pleased to know that it’s quite easy to do. In this article, we’ll show you how to add a login link to your menu using the wp_nav_menu_items filter.

The first step is to create a function that will add the login link to the menu. In this example, we’ll call it wpturbo_add_login_link_to_menu(). This function takes two parameters: $items (the HTML for the menu items) and $args (an array of arguments that were passed to wp_nav_menu()).

Inside the function, we check if the menu location identifier is primary. If you’re using a different menu location, replace primary with the appropriate identifier.

Next, we use the is_user_logged_in() function to check if the user is logged in. If they are not logged in, we append a new list item to the menu with the login link. In this example, we’re using the wp_loginout() function to generate the login link. The first argument is the URL to redirect to after logging in, and the second argument is a boolean flag that determines whether or not to display the link as a button.

Finally, we return the updated HTML for the menu items using the return statement.

The last step is to hook our function into the wp_nav_menu_items filter using the add_filter() function. The first argument is the name of the filter, followed by the name of our function, and then two additional parameters, which are the priority and the number of arguments that our function accepts.

Once you’ve added this code to your theme’s functions.php file, you should see a new login link in your navigation menu that will only appear if the user is not already logged in.

Register an account to save your snippets or go Pro to get more features.