How to Add a Login Link to the wp_nav_menu in WordPress

Home » Snippets » How to Add a Login Link to the wp_nav_menu in WordPress

Created with:



Creator: Alex

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

Having a login link in your website’s navigation menu can provide an easy and quick way for users to log in to their accounts. However, WordPress doesn’t come with a built-in option to add a login link to the navigation menu. In this article, we’ll show you how to add a login link to the wp_nav_menu in just a few simple steps. Let’s dive in!

					function wpturbo_add_login_link( $items, $args ) {
    if ( $args->theme_location == 'primary' ) {
        if ( ! is_user_logged_in() ) {
            $login_link = '<li class="menu-item"><a href="' . wp_login_url() . '">' . __( 'Login', 'wpturbo' ) . '</a></li>';
            $items .= $login_link;
    return $items;
add_filter( 'wp_nav_menu_items', 'wpturbo_add_login_link', 10, 2 );

The wpturbo_add_login_link() function hooks into the wp_nav_menu_items filter and allows us to modify the menu items that are displayed. It takes in two arguments, $items and $args. $items is the menu items itself stored as a string, and $args is an object containing the current menu configuration.

We check whether the current menu is the primary menu location and that the user is not presently logged in by using the is_user_logged_in() function. If the user is not logged in, we create a $login_link variable with the HTML markup that we want to use for our login button.

$login_link = '<li class="menu-item"><a href="' . wp_login_url() . '">' . __( 'Login', 'wpturbo' ) . '</a></li>';

The $login_link variable here contains an HTML li element with a class of menu-item which ensures that it takes on the same styling as the other menu items. The link is defined by an anchor tag with an href attribute that points to the WordPress login URL. The value of the text inside the anchor tag, ‘Login’, is made translatable using the __() function.

Finally, we concatenate this $login_link variable to the $items variable, so that it gets added to the end of the menu items list that is returned.

$items .= $login_link;

The modified $items variable with the appended $login_link HTML will then be returned to the filter hook which will replace the original menu items with the modified ones.

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