How to place Login/Logout link in submenus of WordPress

Sometimes you need to place a Login/Logout link in your site's menu. Even deep in submenus. So I will show you how to do that. This is an universal (for custom menus) way.

First you must find where your menu is generated. So in Dashboard->Appearance->Menus you must find the menu, where you want the Login/Logout link to be. You must find where this menu is bind. Means, in which location (spot) it will be shown. Let say the location is "header-menu". The exactly location name depends of the theme.

While we are at menu, you can add a "label", which later will be replaced with exactly login/logout code. You can create an external link at the exactly place, where your Login/Logout link must be. No matter where in the menu tree it will be. It even can be on top level too. Also you can choose to move it later, no problem. Let say you create a link with text "Logout". The text can be anything, but it must be unique in that menu. As URL you can put "#" sign. Again, no matter what you put, it will be replaced later by code. But must be recognized as URL.

Now do a search in theme's files for string "wp_nav_menu". This is the function, which show menus. Find the one, which have "header-menu" in braces. This one we must change.

The function can not be alone on the row. In this case put an "Enter" just before "w" and just after the semicolon. The function can be on several lines, that's OK.

Now look at following code:

ob_start();
wp_loginout('index.php');
var $loginout = ob_get_clean();
ob_start();
wp_nav_menu( array('theme_location'=> 'header-menu', 'menu_class'	=> 'sf-menu') );
var $nav_menu = ob_get_clean();
echo preg_replace('/<[^<>]*>Logout<[^<>]*>/s', $loginout, $nav_menu);

Saw the "wp_nav_menu" function? Yours goes there. Means, replace my function with your function, with all his parameters. This way we save the layout of menu on your site.

Last step: replace your function in the file you find it on. Most likely - "header.php". Means, resulting code, now including your function, replaces the alone function in your theme's file.

Really last step: save the file and upload it to your site. That's all. Now you have Login/Logout link in your menu.

Well, again, this is universal way, but not always easy one. There is several others ways, even a plugin to do same. Your choose.

This entry was posted in Blog, Hacks. Bookmark the permalink.

Leave a Reply