Add a link to your main menu that says "Log in" for visitors and "Log out" for logged-in users.
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 );
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.
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.
main or menu-1. Check Appearance → Menus → Manage Locations.View the site logged out: the menu ends with “Log in”. Log in and reload: it should say “Log out”.