Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a Login/Logout toggle item in WordPress navigation menu. Source: http://rezzz.com/add-login-and-logout-to-your-wordpress-menu/
<?php
//* Add a Login/Logout toggle item in WordPress navigation menu
add_filter('wp_nav_menu_items', 'customprefix_add_loginout_navitem', 10, 2);
function customprefix_add_loginout_navitem($items, $args) {
if ($args->theme_location == 'primary') {
// Replace "primary" with your theme's menu name
if (!(is_user_logged_in())) {
$login_item = '<li class="menu-item login-menu-item"><a itemprop="url" href="/wp-login.php" rel="nofollow">Log in</a></li>';
}
else {
$login_item = '<li class="menu-item logout-menu-item">' . wp_loginout($_SERVER['REQUEST_URI'], false) . '</li>';
}
$items.= $login_item;
}
return $items;
}
<?php
/**
* Redirect admins to WordPress Dashboard and other users to site's homepage after a successful login
* https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect
*
* @param string $redirect_to URL to redirect to
* @param string $request URL the user is coming from
* @param object $user Logged user's data
* @return string
*/
add_filter( 'login_redirect', 'customprefix_login_redirect', 10, 3 );
function customprefix_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
global $user;
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( 'administrator', $user->roles ) ) {
// redirect them to the default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}
<?php
//* Redirect all users to site's homepage after logout
add_filter( 'logout_redirect', create_function( '$url,$query,$user', 'return home_url();' ), 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.