Dynamically add login/logout link to a WordPress menu


Using ‘wp_nav_menu_items’ filter we can modify wordpress menu and able to add or remove links.Following code will add dynamic login and logout link to a wordpress menu which primary location is ‘topmenu’.

add_filter('wp_nav_menu_items', 'wp_login_logout', 10, 2);

function wp_login_logout($items, $args) {
 if($args->theme_location =='topmenu'):

 if (is_user_logged_in()) {
 $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
 } else {
 $items .= '<li><a href="'. wp_login_url(get_permalink()) .'">Log In</a></li>';
 }
 return $items;
 endif;
 
return $items;
}

You just need to add above code in your functions.php file and its working fine!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s