• Home
  • About
    • Contact
  • WordPress
    • Plugins
    • Themes
    • iThemes
    • Builder
    • Tips and Tricks
  • Demos and Tutorials
    • Flexible Responsive Layouts using CSS in Builder

Enhancing your WordPress 3 menus

By Ronald
Thursday, November 25th, 2010

WordPress 3 comes with integrated menu management. Although still a bit quirky at times, it makes creating and managing (navigation) menus a breeze. However, now that creating and displaying a menu takes nothing more than one line of code (wp_nav_menu), we appear to have lost the ability to “manually” add our own stuff.

For instance, by design, there is no “home” link on any menu. Though it is easy to create a custom menu item in the menu management, there is an easier way, using WordPress filters.

The navigation menu can be “filtered”, and so can the navigation menu items. This allows us to add menu items at will.

Inspired by a support request, I did a bit of digging, the result are the following three code snippets, that you can add to your themes functions.php file and will add a login/logout link, add a search field or a Home Page link to your WordPress 3 navigation menu.

  • Add a login/logout link to your navigation menu
  • Add a search field to your navigation menu
  • Add a Home Page link to your navigation menu

Add a login/logout link to your navigation menu

add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {

		ob_start();
		wp_loginout('index.php');
		$loginoutlink = ob_get_contents();
		ob_end_clean();

		$items .= '<li>'. $loginoutlink .'</li>';

	return $items;
}

Explanation:

First we add a function add_login_logout_link to the wp_nav_menu_items filter. Then, the ob_start, ob_get_contents and ob_end_clean (lines 4, 6 and 7) functions are “output Buffering” PHP functions that will “intercept” the information that would otherwise be sent to the browser. wp_loginout('index.php'); will add the logic and html code to login (if not logged in yet), or logout (if logged in). Since we don’t want to send that code to the browser yet, we “capture” the output (using ob_get_contents) in a variable ($searchform), and finally include that variable as a list item in the menu.

Add a search field to your navigation menu

add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {

		ob_start();
		get_search_form();
		$searchform = ob_get_contents();
		ob_end_clean();

		$items .= '<li>' . $searchform . '</li>';

	return $items;
}

Create your own searchform template

The add_search_box function will include the default searchform in the menu bar. This however may not be the desired layout (perhaps it contains preceding text “search:” and a “search” button), so you should create a template file searchform.php in your theme template directory, and add the following code:

<form method="get" class="search-form" id="search-form" action="<?php bloginfo( 'home' ); ?>/">

	<div class="formfield">
		<input class="formInputText" type="text" name="s" id="search-text" value="Search ..." size="12" maxlength="16" tabindex="1" onfocus="if (this.value == 'Search ...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search ...';}" />
	</div>
	
</form>

Optionally, you can add styling to your form to match your navigation style, using (for example!):

input.formInputText {
	margin-top: 7px;
	color: #666;
	padding: 3px;
	background: #ccc;
}

input.formInputText:hover {
    cursor: help;
    color: 555;
    background: #ccc;
}

Add a Home Page link to your navigation menu

add_filter( 'wp_nav_menu_items', 'add_home_link', 10, 2 );
function add_home_link($items, $args) {

		if (is_front_page())
			$class = 'class="current_page_item"';
		else
			$class = '';

		$homeMenuItem =
				'<li ' . $class . '>' .
				$args->before .
				'<a href="' . home_url( '/' ) . '" title="Home">' .
				$args->link_before . 'Home' . $args->link_after .
				'</a>' .
				$args->after .
				'</li>';

		$items = $homeMenuItem . $items;

	return $items;
}

props to Division by Zero

Add these to a specific menu only

The filter will run for each menu you have defined, so the samples above will be added to each one of those. This may not always be what you want, so to add the desired code to a specific menu location only, add a condition to the code, to make sure the code only executes for a specific menu location:

function add_login_logout_link($items, $args) {

	if($args->theme_location == 'Primary') {

		ob_start();
		wp_loginout('index.php');
		$loginoutlink = ob_get_contents();
		ob_end_clean();

		$items .= '<li>'. $loginoutlink .'</li>';

	}
	return $items;
}
Categories : Code Snippets, Tips and Tricks, Wordpress
Tags : filters, functions, home, navigation, Wordpress

Comments

  1. wp-popular.com » Blog Archive » Enhancing your WordPress 3 navigation menus :: van Weerd says:
    November 27, 2010 at 04:15

    [...] is the original post: Enhancing your WordPress 3 navigation menus :: van Weerd Tags: logout-link, menu, menus, [...]

    Reply
  2. Tom says:
    December 30, 2010 at 21:59

    Hi, I’m getting error when I add your login and search functions to the funtions.php

    for the login i get the error
    Fatal error: Call to undefined function add_filter() in C:\xampp\htdocs\jameswp\wp-includes\functions.php on line 4304
    that on the 1st line of your code

    and then on the search function I get this error I get the same error

    Reply
  3. Tom says:
    December 30, 2010 at 22:54

    found the answer to my question at
    http://www.howtodowebmarketing.com/2010/02/08/fatal-error-call-to-undefined-function-add_filter/

    Thanks

    Reply
  4. How to automatically add a search field to your navigation menu says:
    January 11, 2011 at 08:06

    [...] to Ronald for the cool tip! If you enjoyed this article, please consider sharing it! tweetmeme_style = [...]

    Reply
  5. Rick Beckman says:
    January 11, 2011 at 10:11

    I saw your trick for adding the search form to the nav menu on WPRecipes.com, and noticed right away that it can be simplified a bit.

    The login/out link code may be simplified as well:

    add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
    function add_login_logout_link($items, $args) {
    $loginoutlink = wp_loginout('index.php', false);
    $items .= '<li>'. $loginoutlink .'</li>';

    return $items;
    }

    Reply
  6. How to automatically add a search field to your navigation menu | The best Tutorials says:
    January 12, 2011 at 01:11

    [...] to Ronald for the cool [...]

    Reply
  7. Website Design, Web Development, Content Management System, CMS Web Sites, Ecommerce Websites – Broadys Web Design | How to automatically add a search field to your navigation menu says:
    January 12, 2011 at 04:32

    [...] ob_end_clean(); $ items .= '<li>' . $ searchform . '</li>'; return $ items; }Thanks to Ronald for the cool tip!GD Star Ratingloading…Share this Related posts:WordPress tip: Remove WP 3.1 [...]

    Reply
  8. Automatically Add Search Field On Wordpress 3.0 Navigation Menu Easily says:
    January 12, 2011 at 11:38

    [...] . $searchform . '</li>'; return $items; }Hope this tutorial useful for you.Via: VanWeerd.You Might Like Theses Posts:Place Thesis Main Navigation Menu Below HeaderThesis Theme Is One Of [...]

    Reply
  9. How to Add a Login/Logout button to your Wp Menu | WpCode says:
    January 13, 2011 at 00:03

    [...] to Vanweerd.com for this hack. With this code you can add a Login/Logout button to your WordPress 3.0 [...]

    Reply
  10. How To Add Login/Logout link To Your Navigation Menu says:
    January 18, 2011 at 06:46

    [...] thanks to Ronald for the cool [...]

    Reply
  11. How To Add WP Login Link to Your Navigation Menu Automatically # WordPress Tricks & Tips says:
    January 22, 2011 at 01:30

    [...] That’s it, now you menu navigation will be added wp_loginout() automatically. More details about what going on this code you can read it here [...]

    Reply
  12. Cara Menambah Menu Home pada Menu Navigasi WordPress says:
    January 22, 2011 at 06:41

    [...] kontribusi dari sini dan [...]

    Reply
  13. zeaks says:
    January 22, 2011 at 07:27

    Thanks for this info. Is there a way to style the loginout link in the menu? I’ve tried .menu-item-logoutlink and variations but I can’t figure it out. I’m also unable to see how to do it through firebug.

    Reply
    • Ronald says:
      January 23, 2011 at 12:15

      I see you managed

      Reply
  14. zeaks says:
    January 22, 2011 at 17:41

    With the loginout link in the navigation, is it possible to also show the “Dashboard” link?

    Reply
    • Ronald says:
      January 23, 2011 at 12:15

      Why not wait till WordPress 3.1 is released: http://vanweerd.com/a-quick-look-at-some-new-features-in-wordpress-3-1/#admin_bar

      Reply
      • zeaks says:
        January 25, 2011 at 18:45

        I forgot about the admin bar,thanks

        Reply
  15. Add login link Automatically to Twenty Ten Menu | Zeaks Blog says:
    January 23, 2011 at 05:12

    [...] mostly from Vanweerd.com Enhancing your WordPress 3.0 [...]

    Reply
  16. How To Add a login/logout link to Your Navigation Menu / WordPress Themes, Plugins & Development says:
    January 25, 2011 at 15:13

    [...] First we add a function add_login_logout_link to the wp_nav_menu_items filter. Then, the ob_start, ob_get_contents and ob_end_clean (lines 4, 6 and 7) functions are “output Buffering” PHP functions that will “intercept” the information that would otherwise be sent to the browser. wp_loginout('index.php'); will add the logic and html code to login (if not logged in yet), or logout (if logged in). Since we don’t want to send that code to the browser yet, we “capture” the output (using ob_get_contents) in a variable ($searchform), and finally include that variable as a list item in the menu. via VanWeerd [...]

    Reply
  17. How to automatically add a search field to your navigation menu | Wordpress Farm says:
    January 28, 2011 at 02:18

    [...] to Ronald for the cool [...]

    Reply
  18. Add login link Automatically to Twenty Ten Menu says:
    February 8, 2011 at 13:40

    [...] mostly from Vanweerd.com Enhancing your WordPress 3.0 [...]

    Reply
  19. How to add a search field to your navigation menu | Fazreen says:
    February 14, 2011 at 18:32

    [...] thanks to Ronald for the nice [...]

    Reply
  20. How To Add Login/Logout link To Your Navigation Menu | Fazreen says:
    February 14, 2011 at 18:55

    [...] thanks to Ronald for the cool [...]

    Reply
  21. How to automatically add a search field to your navigation menu - WPInsite says:
    March 1, 2011 at 00:00

    [...] $items .= '<li>' . $searchform . '</li>'; return $items; }Thanks to Ronald for the cool tip!VN:F [1.9.7_1111]please wait…Rating: 0.0/5 (0 votes cast)Share this Related [...]

    Reply
  22. Colman Carpenter says:
    March 25, 2011 at 13:08

    Hi,

    Great article!

    Having a bit of a problem, though, trying to add a login/out link to a specific menu in Headway. Headway doesn’t use standard menu areas (primary, secondary, etc), so I’m trying to identify based on the menu name using the line

    if($args->menu == ‘Account’) {

    I have also tried using the menu id ’7′

    This isn’t working though :(

    Can you help?

    Reply
    • Ronald says:
      March 28, 2011 at 11:53

      remove the conditional code, and try

      add_filter('wp_nav_menu_Account_items', 'add_login_logout_link', 10, 2);

      Reply
  23. blackbookdesign says:
    April 4, 2011 at 05:22

    Hi,

    thx for the tips.
    cheers :)

    Reply
  24. yoyo says:
    June 10, 2011 at 03:29

    hi .. i still don’t understand on how to add homepage link into my navigation menu .. just copy all the codes or i must edit it first ? how about the color codes does it mean same with others or i must edit the blue colors? sorry i’m newbie on this..

    Reply
    • Ronald says:
      June 12, 2011 at 22:41

      Follow the instructions here: http://vanweerd.com/enhancing-your-wordpress-3-menus/#add_home

      Reply
  25. Bart says:
    June 12, 2011 at 17:06

    Hoi Ronald.

    Quick question. Seems like the logout link is being added the every custom menu I create. I only want it to show up in the nav bar. Can the code easily be tweaked for this to be the case?

    Kind regards

    Bart

    Reply
    • Ronald says:
      June 12, 2011 at 22:34

      Hi Bart,

      check the last paragraph of the article, titled: “Add these to a specific menu only”

      Reply
  26. Bart says:
    June 13, 2011 at 11:14

    Bit embarrassed here, I didn’t see that part.

    Anyway I tried everything but somehow I am missing something. My main navigation menu is called ‘Main’ so I suppose the code should look like this:


    add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
    function add_login_logout_link($items, $args) {

    if($args->theme_location == 'Main') {

    ob_start();
    wp_loginout('index.php');
    $loginoutlink = ob_get_contents();
    ob_end_clean();

    $items .= ''. $loginoutlink .'';

    }

    return $items;

    }

    I don’t get an error, I just don’t see the link anymore. Confused here :)

    Reply
    • Ronald says:
      June 14, 2011 at 10:39

      Is that the theme location as can be see in wp-dashboard > Appearance > Menus?

      Reply
  27. bart says:
    June 14, 2011 at 14:00

    Yup it’s called ‘Main’

    Strange…

    Reply
  28. Aggiungere il campo cerca nel menù di navigazione wp » paologironiblog says:
    November 8, 2011 at 14:35

    [...] semplice trick trovato su WpRecipes (ma l’originale è in questo articolo) per inserire nella barra di navigazione di WordPress 3.* il campo cerca. Semplice e utile. Basta [...]

    Reply
  29. How to Add a Login/Logout Link to Your WordPress Menu | SNS Online says:
    January 21, 2012 at 17:43

    [...] following method found at Vandweerd.com will automatically detect whether a user is logged in or not and put a login or a logout link right [...]

    Reply
  30. wp-coder.net » How to Add a Login/Logout Link to Your WordPress Menu says:
    January 22, 2012 at 04:01

    [...] following method found at Vandweerd.com will automatically detect whether a user is logged in or not and put a login or a logout link right [...]

    Reply
  31. A Free wordpress newsletter » How to Add a Login/Logout Link to Your WordPress Menu says:
    January 22, 2012 at 04:02

    [...] following method found at Vandweerd.com will automatically detect whether a user is logged in or not and put a login or a logout link right [...]

    Reply
  32. Jon says:
    February 7, 2012 at 13:03

    Thanks the login/out code worked. But what about a register/admin sub-menu to it?

    Reply
  33. Add login link Automatically to Twenty Ten Menu says:
    February 26, 2012 at 22:57

    [...] mostly from Vanweerd.com Enhancing your WordPress 3.0 menu. Style WordPress 3.0 Menu Items | Menu Classes Add a back to [...]

    Reply
  34. Bronwyn says:
    March 8, 2012 at 07:25

    HI,

    this is great and works well, but we’d like it to redirect to a specific page on our website e.g. /?page_id=12 instead of redirecting to the default WP login. is this possible?

    many thanks

    Reply
    • Ronald says:
      March 14, 2012 at 14:15

      you don’t need this code for that. Add a custom menu item via wp-dashboard > Appearance > Menus, and specify the target URL

      Reply
      • Bronwyn says:
        March 15, 2012 at 01:22

        We’ve tried that but how do we make the same menu link switch between Logout and Login i.e. when logged in it says Logout and when logged out it says login. There seems to only be one option to set the label?

        Reply
  35. Aggiungere il campo cerca nel menù di navigazione wp » paologironiblog says:
    March 30, 2012 at 22:03

    [...] addthis_share = [];}Un semplice trick trovato su WpRecipes (ma l’originale è in questo articolo) per inserire nella barra di navigazione di WordPress 3.* il campo cerca. Semplice e utile. Basta [...]

    Reply
  36. Carlo says:
    April 23, 2012 at 18:04

    Hello! I tried to put the 2 functions but in the search form to add the custom appears out of the menu bar, any help?
    my code:
    add_filter(‘wp_nav_menu_items’, ‘add_login_logout_link’, 10, 2);
    function add_login_logout_link($items, $args) {

    ob_start();
    wp_loginout(‘index.php’);
    $loginoutlink = ob_get_contents();
    ob_end_clean();

    $items .= ”. $loginoutlink .”;

    return $items;
    }

    add_filter(‘wp_nav_menu_items’,'add_search_box’, 10, 2);
    function add_search_box($items, $args) {

    ob_start();
    get_search_form();
    $searchform = ob_get_contents();
    ob_end_clean();

    $items .= include(TEMPLATEPATH . ‘/search-form.php’);

    return $items;
    }
    Thanks!

    Reply
  37. How to Add a Login/Logout Link to Your WordPress Menu | Coluce says:
    June 9, 2012 at 02:51

    [...] following method found at Vandweerd.com will automatically detect whether a user is logged in or not and put a login or a logout [...]

    Reply
  38. Bbvoncrumb says:
    November 17, 2012 at 10:12

    Thanks a lot. After much searching a failed results even on the WordPress forums, this worked perfectly.

    Thanks!

    Reply
  39. Pixel Fish says:
    December 11, 2012 at 04:25

    I have added the Login/log out code to my functions file and it works perfectly.
    I now need to remove it but even after it has been removed from functions.php, it is still being displayed in the menu.

    How do I remove it?

    Reply
    • Ronald says:
      December 11, 2012 at 13:37

      Probably a caching issue, disable caching plugins, if any, clear the plugins cache and/or clear your browser cache.

      Reply
  40. Test Building A Plugin Post | clearoutput says:
    January 18, 2013 at 02:26

    [...] This article covers the code for adding the login/out menu: http://vanweerd.com/enhancing-your-wordpress-3-menus/#add_login [...]

    Reply
  41. How to Automatically Add a Search Field to Your Navigation Menu! says:
    January 22, 2013 at 08:17

    [...] to Ronald for the cool [...]

    Reply
  42. jane says:
    January 29, 2013 at 01:21

    Hoping you can help – I love the code that adds a search bar to the menu, it worked beautifully. However, my theme also is using a menu call function in the sidebar. How can I get the search box to only show up in the top navigation?

    Thanks -

    Reply
    • jane says:
      January 29, 2013 at 01:25

      Should mention also, that the way the designer set up the menus doesn’t seem to utilize the “Primary” “Secondary” theme locations. Those are blank, yet there are still two menus – one called “Main Menu” and the other called “Social.”

      Reply
      • jane says:
        January 29, 2013 at 01:32

        Tried this:

        add_filter('wp_nav_menu_items','add_search_box', 10, 2);
        function add_search_box($items, $args) {

        if($args->theme_location == 'Main Menu') {

        ob_start();
        get_search_form();
        $searchform = ob_get_contents();
        ob_end_clean();

        $items .= '' . $searchform . '';
        }
        return $items;
        }

        But it only removes both search bars. Any suggestions?

        Reply
      • Ronald says:
        January 29, 2013 at 15:20

        Hi,

        the code relies on the wp_nav_menu function, using the menu locations.

        Removing another search box is unrelated to this code, and can be done by either editing the theme template files, or use css to hide the search form.

        Reply
  43. Add a Search form to your Navigation menu on WordPress says:
    March 21, 2013 at 12:55

    [...] all you have completed. Thanks to Ronald for the cool [...]

    Reply
  44. Bill says:
    April 22, 2013 at 06:47

    Hey there!

    First off, these are very useful. Unfortunately.. it didn’t come out as I thought it would on my site and kinda ruined my theme. I fixed that though, had backups and whatnots. But now I have a problem with removing this search box off of the header menu.

    Care to shed any light on this? Thanks a lot =]

    Reply
  45. Michele says:
    May 16, 2013 at 22:57

    Hi,
    I am using twenty twelve with a child theme. I have a link in my primary nav menu where I have an link for “My Account” which has a sub menu with a “Login/Register” link that redirects to a modified wp-login.php. Is it possible for me to turn the “Login/Register” link into a “Logout” link when a user is logged in? If it is possible, would you know how I could accomplish this, or point me in the right direction?

    I have been searching for quite some time with no luck. I would like to leave the menu intact since the sub menu will have more links added to it.

    Thank you

    Reply

Leave a Reply

Click here to cancel reply.