
How to Add a Login/Logout Link to the Main Menu Without Using Plug-ins
- April 14, 2016
- Leave a comment
The login functionality to a website is an essential part of any application. It is used by the administrator to manage the entire website or to allow visitors to perform different calls-to-action according to his/her set of permissions.
To enable visitors to follow through on calls-to-action by logging into the website, there must be a login link. According to the standard for friendly graphical user interfaces, the link must be placed in a prominent location like the Main Menu.
There are many ways to add the login/logout link in menus, either by coding or using plug-ins. Plug-ins, however, can sometimes be vulnerable to security threats. Thus, WordPress has provided a filter for the main menu to alter the final output.
To add a login/logout link at the end of the Main Menu, you can use wp_nav_menu_items filter. This filter required two parameters:
- $items, contains the HTML of the menu list
- $args, an object containing wp_nav_menu() arguments
To implement this functionality, you can add the following code in your functions.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function add_login_logout_link($items, $args) { // Turn on output buffering ob_start(); // Display login / logout link with optional parameter for redirection wp_loginout('index.php'); // Store the content of output buffer $loginoutlink = ob_get_contents(); // Trun off the output buffer ob_end_clean(); // Add the login / logout link at the end of menu HTML content and return $items .= '<li>'. $loginoutlink .'</li>'; return $items; } add_filter('wp_nav_menu_items', 'add_login_logout_link'); |
It will then display the login/logout link at the end of Main Menu (primary menu) for both anonymous users and for logged-in users.
User Comments