Log In / Log Out Item in the Menu
Appends a "Log in" link to your main menu for visitors and a "Log out" link for logged-in users, returning them to the same page.
Opens WPIDE on
Code
add_filter( 'wp_nav_menu_items', function ( $items, $args ) {
$location = 'primary'; // Theme menu location.
if ( ! isset( $args->theme_location ) || $args->theme_location !== $location ) {
return $items;
}
$current = home_url( add_query_arg( array() ) );
if ( is_user_logged_in() ) {
$items .= '<li class="menu-item wpide-menu-logout"><a href="' . esc_url( wp_logout_url( $current ) ) . '">Log out</a></li>';
} else {
$items .= '<li class="menu-item wpide-menu-login"><a href="' . esc_url( wp_login_url( $current ) ) . '">Log in</a></li>';
}
return $items;
}, 10, 2 );
Notes
Set $location to your theme's menu location slug. Works with classic menus.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.