Categories
24 Days of WordPress Tutorials

Day 5: Adding custom WordPress 3 menus to your theme

In Day 4: Using WordPress 3 Custom Menus I showed you how to get the most out of the custom menu function introduced with WordPress 3. In this Fifth Day of WordPress I’m going to take that a step further and show you how to add new Theme Locations for your menus. This procedure can be used to add new menus to existing themes like twentyten and it can be used to add the WordPress 3 custom menu functionality to old themes that don’t have it already installed. I’ll show you how to add the menu function, how to add the menus to your theme files and also talk a bit about the different variables available when you create custom menus. Lots of ground to cover here so let’s get started.

Setting up the custom menu function

To get custom menus to work within your theme you first have to add the function to your theme. That’s done in the functions.php file. The basic function you need to add looks like this:


<?php 
register_nav_menus( array(
	'Menu1' => 'Menu 1 Name',
	'Menu2' => 'Menu 2 Name',
	'Menu3' => 'Menu 3 Name',
) );
?>

The first part of the array variable (Menu1, Menu2, Menu3) are the elements used to call the menu from the template files. The second part (Menu 1 Name etc) is the menu name as it will appear inside the Menus function in WordPress.

If you’re working with a theme that doesn’t have the WordPress 3 menu function already installed, or if you want to add more menus, you simply copy the code above, paste it into functions.php and customize it to your liking. If you are working with a twentyten child theme you need to unplug the twentyten menu setup first. I already covered how to do this in Day 2: Creating a WordPress Child Theme the Smart Way but it doesn’t hurt to repeat it. Simply create a functions.php file in your child theme folder, copy and paste this block of code in and you’re good to go:


<?php 

// Remove the default 'register_nav_menus' function
function remove_register_nav_menus() {
    remove_action( 'twentyten_setup', 'register_nav_menus' );
}
 
// Call 'remove_register_nav_menus' (above) during WP initialization
add_action('after_setup_theme','remove_register_nav_menus');
 
// Register new 'register_nav_menus' function by running 'register_nav_menus' on the 'twentyten_setup' hook. */
add_action( 'twentyten_setup', 'register_nav_menus' );
 
// This child theme uses wp_nav_menu() in two locations.
register_nav_menus( array(
	'primary' => 'Header Menu',
	'secondary' => 'Footer Menu',
) );

?>

In this case I’ve created two menus: Header Menu and Footer Menu. And when you

Adding a new menu to a theme template

New WordPress 3 menuWhen you’ve added the code above to your functions.php file you’ll find a new Theme Location option in the Menus area in the WordPress admin panel. But to get the menu to display somewhere in your theme you have to do some more work. By default twentyten has the primary Header Menu installed so we don’t have to worry about that as long as we set the variable name to “primary”. As for the Footer Menu we have to add that one manually into the theme files. Since we want it to appear in the footer we create a copy of the footer.php file from the twentyten folder in the child theme folder. This child theme footer.php file will now override twentyten’s footer.php file.

The next step is to add the template tag to call the menu. This is where things get interesting. You can call the menu in two different ways; either based on the name as set by the functions.php file or based on the menu name as defined by the user. If you pick the first (and safest) option this is the code you want to use:


<?php 
	wp_nav_menu(array(
		 'theme_location' => 'primary'
	)); 
?>

If you want to use the second option for some reason (for example if you want to add an optional menu to a free theme) you use this code:


<?php 
	wp_nav_menu(array(
		'name' => 'Menu Name'
	)); 
?>

It’s all pretty self explanatory, but here is a concrete example: If you want to call the footer menu we created above you insert the following block of code into the new footer.php file:


<?php 
	wp_nav_menu(array(
		 'theme_location' => 'secondary'
	)); 
?>

This adds the menu as an unordered list in the footer. Now all that’s left is to style it – but that’s a whole different tutorial.

More options than you’ll ever need

If you go to the twentyten theme and look in header.php you’ll find this block of code on line 85:


<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>

You’ll recognize most of it but there’s more stuff here than I told you to use before. That’s because the wp_nav_menu function comes with an insane ammount of variable options to customize the output. In the case of the twentyten header menu the code says that the div container inside which the menu is wrapped should have a class named “menu-header” attached. This is for styling purposes so you can use different classes or IDs to target different menus. There are tons of other options as well, some more useful than others and you can read all about them in the WordPress Codex function reference page. I recommend you read the page and experiment with the output. It can be quite interesting to see what comes out and the variables open a lot of posibilities for customization. For your reference I rarely use anything more advanced than what you see in the twentyten example above.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
24 Days of WordPress Tutorials

Day 4: Using WordPress 3 Custom Menus

In this Fourth Day of WordPress let’s take a closer look at the new custom Menus function that was introduced with WordPress 3.0. You may already be aware of this function, and you may even have used it before, but it has some pretty nifty uses you may not be aware of, so please read on.

Basic menu creation

Assuming you’re working with a theme that supports WordPress 3 menus, actually making a menu is very easy. I’m using twentyten as an example here but it’s the same for any theme with this function installed. If you haven’t created a custom menu yet WordPress will insert a menu consisting of a Home button plus a list of all your top-level pages. Any children of these pages will be listed in the drop-down elements.

WordPress 3 MenusTo get to the menu option go to Appearance -> Menus. Here you will see the standard Menu dashboard. Opening it for the first time there are no menus defined and it is empty. To start off you need to insert a Menu Name and click the Create Menu button. Now you have a custom menu you can work with.

WordPress 3 MenusAt the top left is a box labeled Theme Locations. Depending on what theme you use there can be one or several locations listed here. Below each location is a drop-down box where you can pick what menu goes in that alocation. For twentyten there is one theme location and that’s where you want your custom menu to appear so select it and click Save.

Adding new buttons to the WordPress 3 menuNow it’s time to add some menu elements. You can add one of three types of elements: Custom lins (pointing to anywhere within your site or on the web), Pages and Categories. This is what makes the menu feature so powerful: You can now create a custom menu with a mix of different types of links. In the past this required either a hard-coded menu, a pile of theme hacks that were quite complicated or a dedicated plugin. No more of that nonsense. To add menu items simply select them and click Add To Menu and they appear. Note that if you want a dedicated Home button select the View All tab under Pages and you’ll be able to select it from the list.

Moving WordPress 3 menu itemsNow comes the fun part: With menu items added to your custom menu, you can move them around and organize them in hierarchies simply by clicking and dragging them around (see image above). This means you can modify your menu on the fly to fit your own preferences or those of your visitors. In short, your menus are not static any more but dynamic entities that can be changed and configured at any time.

When you click the Save Menu button and go to your site you’ll see that your new menu has replaced the default one. Very neat. But that’s just the beginning.

Menu item customization

Each of your menu items can be customized in some useful and surprising ways. I’ll give you some examples.

WordPress 3 menu item configurationFor each menu item you can make in-menu changes to the Navigation Label (the actual text that appears in the menu) and the Title Attribute (the screentip that pops up when people hover over it). For the custom link menu items you can also change the URL. To access these options simply click the little down arrow on the right side of each item tab. As a rule of thumb every menu item should have a defined and descriptive Title Attribute. This is both for people who are accessing your site using a text-to-speech browser, text-only browsers and also for your primary blind reader Google. When you make changes to the menu items remember to click the Save Menu button in the top right corner, otherwise the changes are not saved. From within the menu item configuration area you can also Remove any menu item from this menu. Doing this does not delete the content, just removes the menu item.

Fancy Menus With HTML

Fancy WordPress 3 menus with HTMLThat’s all well and good, but I’m pretty sure if you’ve played around with these menus at all you already knew all of this. So here’s something you most likely didn’t know: The Navigation Label field can receive HTML code! The image above shows the header menu we built for the 12×12 Vancouver Photo Marathon website. As you can see each of the menu items contains more than just one or two words, and the content within each item is split into two separate styles: an all-caps main title and an all lowercase description. To achieve this we simply inserted some HTML into the Navigation Label field of the menu items as you see in the image below.HTML in WordPress 3 menusNow just so we’re clear: Getting this to work requires quite a bit of style code – it’s not automatic.

I’ve tested this extensively, and the menu items will simply feed out pretty much any HTML you stuff the Navigation Label field with. That means you can create some pretty ridiculous conflicts if you’re not careful. For example, you could insert an <a href> tag in the Navigation Label field that points somewhere entirely different than the menu item itself. This can produce some rather unfortunate results. You can also stuff it with active JS and even embed and iframe codes. I do not recommend it. Sticking with simple <span> tags and other stylistic elements is safe.

Custom Menu Widget

Custom Menu WidgetIf you have already filled out all your theme menu areas or you want to create an additional menu somewhere else you can use the Custom Menu widget. This widget allows you to place any of the menus you create within the Menus area in any widgetized area. That means you can add a custom menu to your sidebar or any other widgetized box, for example in the footer. Twentyten comes with a huge pile of widgetized areas you can populate with custom menus.

To use the Custom Menu Widget to to Appearance -> Widgets, locate the Custom Menu widget and drag-and-drop it to your desired widgetized area. Once there you can give the custom menu a title (if you don’t give it a title it will appear without one) and select which of your custom menus to display.

Using the custom menu widget in conjunction with the theme menus you can create a whole variety of custom navigation scenarios depending on where the user lands on your site. This shows just how useful and revolutionary the custom menu function in WordPress 3 really is. Now that you know, go out and make some cool menus of your own!

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.

Categories
Tutorials WordPress

Highlight Current Page or Category in WordPress 3.0 Menus

Almost two years ago I published an article on how to create custom WordPress menus that highlighted the current page. It’s still one of the most popular posts on this site, and for good reason: Current page highlighting is vital to ensure a good user experience for your visitors. Without current page highlighting it’s hard for the visitor to know if she is on the correct page or not. Now it’s time to upgrade that tutorial to incorporate the new custom menu functionality in WordPress 3.0 and also add some new functionality.

WordPress 3.0 menus simplify everything… once you understand them

One of the major improvements shipped in WordPress 3.0 was the custom menu functionality. In the past menus were restricted to either simple page or category lists, hard-coded menus stored in the theme files or cumbersome 3rd party plug-ins. No such trouble any more. Custom menus are now available from right within the WordPress admin panel, found under the Appearance tab. And even if you have an older theme that doesn’t support the new menus you can still use them in your sidebar as widgets.

I’m not going to cover how to use the menus from within the admin panel. For that I recommend you read this WordPress Codex article that explains it quite well. Instead I’m going to talk about what you can do with these menus styling wise.

Dissecting the stock menu output

To see what’s possible with these new menus let’s first take a look at the code output from the stock menus. In this example I’ve created one menu with the name “My First Menu” and added it to the site using a sidebar widget. The menu has three buttons; Home pointing to the home page, About pointing to the About page and Contact pointing to the Contact page. (To make the code easier to read I’ve removed the sidebar <ul> and <li> tags so you only see the actual menu output.)


<div class="menu-My-First-Menu-container">
	<ul id="menu-My-First-Menu" class="menu">
		<li id="menu-item-37" class="menu-item menu-item-type-custom current-menu-item current_page_item menu-item-home menu-item-37">
			<a title="Home" href="http://mysite.com/">Home</a>
		</li>
		<li id="menu-item-38" class="menu-item menu-item-type-post_type menu-item-38">
			<a title="About" href="http://mysite.com/about/">About</a>
		</li>
		<li id="menu-item-39" class="menu-item menu-item-type-post_type menu-item-39">
			<a title="Contact" href="http://mysite.com/contact/">Contact</a>
		</li>
	</ul>
</div>

The key information for this tutorial can be found on line 4:

The first list item has an ID attached to it and then a huge array of classes. They are: “menu-item”, “menu-item-type-custom”, “current-menu-item”, “current_page_item”, “menu-item-home” and “menu-item-37”. Of these the three that matter to us are “current-menu-item”, “current_page_item” and “menu-item-home”. Using these custom classes you can create custom styles that highlight or otherwise affect only certain elements:

.current-menu-item { } targets only the menu item the visitor pressed to get to the menu. This goes for categories as well as pages.

.current-page-item { } targets only the current menu item if that menu item is pointing to a page and the visitor is on that page.

.menu-item-home { } targets only the menu item that points to the root or home page of the site.

So, to answer the question from the original artice: How do I highlight the current page in my menu? The answer is create a custom class style with the name .current-menu-item. As a bonus this style will not only target your pages but also your category index pages and your home page. In the past you had to create separate styles for these.

Going deeper with child pages

But this is just the beginning. With the new WordPress menus you can create custom styles that target more than just pages and category indexes. It turns out the code output for these custom menus is highly dynamic and it interacts with all the content on your page whether you actually use the menus or not. The code output above was generated after clicking on the home page and thus resulted in the three classes listed above (notice those three classes are not present in the two other list items). But what if you went to a page that was a child of one of the menu pages? In the past that would mean the parent page would not be highlighted in the menu. But now it can.

The code below was grabbed from the same site as before after I opened a page for which the About page is the parent:


<li id="menu-item-38" class="menu-item menu-item-type-post_type current-page-ancestor menu-item-38">
	<a title="About" href="http://mysite.com/about/">About</a>
</li>

Look closely at the class array and you’ll find this new class: “current-page-ancestor”. This class is activated every time the visitor opens a page that has a parent page that is featured on the menu. That means you can use this class to highlight the parent in the menu. The easiest way to do this is by simply adding the new class to the style of the original .current-menu-item class:

.current-menu-item, current-page-ancestor { } targets either the menu item for the current page or the menu item for the parent page if a child page is visited.

Category highlighting for single posts

It gets even more interesting when we look at category menu items. Like in the past you can create menus that point to category archives. And you can use the .current-menu-item class to highlight the current category in the menu if you’re on the category index page. But what if you want to highlight the category (or categories) of a particular post when that post is open? Again there are custom classes for this:


<li id="menu-item-40" class="menu-item menu-item-type-taxonomy current-post-ancestor current-menu-parent current-post-parent menu-item-40">
	<a title="Commercials" href="http://mysite.com/category/commercial/">Commercial</a>
</li>

Here the three classes “current-post-ancestor”, “current-menu-parent” and “current-post-parent” are what matters. Either of the three will allow you to highlight the category (or categories) the current post belongs to, but they each work in different ways:

.current-post-ancestor { } targets the menu item as long as the category the menu item points at is an ancestor of the post (so regardless of whether the post is in the category or in a sub-category under the category)

.current-menu-parent { } targets the menu item if it is the parent of the menu to which the post belongs (yes, it’s confusing).

.current-post-parent { } targets the menu item only if the category is the direct parent of the post (menu item will not be highlighted if the post only belongs to a category that is a child of the category the menu item points to).

Bottom line: The style that highlights pages, categories and parents

Because of how this new menu system is set up, and because it works so well you only really need to create one custom style if you want to highlight the current page, current category, page parent and category parent in your menu:


.current-menu-item,
.current-page-ancestor,
.current-post-ancestor { }

To get more advanced you can also create separate highlighting styles depending on what type of menu item it is or what relationship it has to the page, post or index. And if you have multiple menus you can create entirely separate style sets for each of these, complete with current page, post and category highlighting. The possibilities are if not endless then at least quite extensive.

Upon first inspection the code output of the new WordPress 3.0 menu system may look quite messy but now that you see what it’s all for I think you’ll agree with me that this heralds in a whole new age of menu customization for theme developers.

If you want to see this stuff in practice head on over to the website for the 12×12 Vancovuer Photo Marathon where I’ve implemented tons of custom menu highlighting.