You can achieve this using the wp_nav_menu_items
hook. Let’s have a look at the following piece of code which shows the login/logout link on the primary
menu location.
add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 );
function wti_loginout_menu_link( $items, $args ) {
if ($args->theme_location == 'primary') {
if (is_user_logged_in()) {
$items .= '<li class="right"><a href="'. wp_logout_url() .'">'. __("Log Out") .'</a></li>';
} else {
$items .= '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">'. __("Log In") .'</a></li>';
}
}
return $items;
}
This is what we have implemented in the above example.
- First added a filter for
wp_nav_menu_items
hook and attached a
function to it. - After checking for
primary
theme location, we have checked whether
user is logged in or not. - If logged in, we have showed the
Log Out
link otherwise theLog In
link. - We have passed the permalink of the currently viewing page to the
login url so that user will be redirected to the current page after
successful login. - We have used the
class="right"
to the above code to meet your
requirement.
You can find a detailed explanation on this blog.