Users & Login PHP Beginner

Add a Log In / Log Out Link to a Menu

Add a link to your main menu that says "Log in" for visitors and "Log out" for logged-in users.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
add_filter( 'wp_nav_menu_items', function ( string $items, stdClass $args ): string {
	if ( 'primary' !== ( $args->theme_location ?? '' ) ) {
		return $items;
	}

	$current = home_url( add_query_arg( [] ) );

	if ( is_user_logged_in() ) {
		$link = '<a href="' . esc_url( wp_logout_url( $current ) ) . '">' . esc_html__( 'Log out' ) . '</a>';
	} else {
		$link = '<a href="' . esc_url( wp_login_url( $current ) ) . '">' . esc_html__( 'Log in' ) . '</a>';
	}

	return $items . '<li class="menu-item menu-item-login">' . $link . '</li>';
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Classic menus can’t change depending on whether someone is logged in. This snippet adds a link at the end of a menu that switches between “Log in” and “Log out” automatically.

How it works

wp_nav_menu_items filters the HTML of a menu’s items before it’s printed. The snippet only changes the menu in the primary location, then adds a list item with the right link. Both links send people back to the page they were on.

The logout link uses wp_logout_url(), which includes the security nonce, so there’s no “Are you sure?” screen.

Things to watch

  • Your theme’s menu location may have a different name, such as main or menu-1. Check Appearance → Menus → Manage Locations.
  • Block themes use the Navigation block instead. Add the Login/out block there.
  • If you use page caching, make sure logged-in users bypass the cache, or the wrong link may show.

How to test it

View the site logged out: the menu ends with “Log in”. Log in and reload: it should say “Log out”.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only