Custom Menu Code Samples

Do you find yourself taking older themes and adding support for Custom Menus? Here are code samples that you can use for just that.

To be clear, this isn’t a full-blown tutorial for Custom Menus. See Justin Tadlock’s excellent post, Goodbye, headaches. Hello, menus! or the wp_nav_menu Codex page for all the juicy details.

First, implement the following in functions.php and header.php.

In header.php:

<?php wp_nav_menu( array( 'container' => false, 'theme_location' => 'primary', 'fallback_cb' => 'mytheme_page_menu' ) ); ?>

This command replaces the previous navigation—usually a list of pages—which moves to the fallback function in functions.php.

In functions.php:

// Enable navigation menu
register_nav_menus( array(
	'primary' => __( 'Primary Navigation', 'mytheme' )
) );

// Add fallback for navigation
function mytheme_page_menu() { ?>
<ul class="menu">
	<li<?php if ( is_home() ) echo ' class="selected"'; ?>><a href="<?php home_url(); ?>">Home</a></li>
	<?php wp_list_pages( 'depth=1&title_li=' ); ?>
</ul>
<?php } ?>

Don’t forget to change “mytheme” in the examples above to the name or slug of your theme.

Next, add the CSS rules for submenu items.

#nav li {
	position: relative;
}
#nav li a {
	display: block;
}
#nav .children .children,
#nav .sub-menu .sub-menu {
	margin-left: 12px;
}
#nav ul ul {
	display: none;
	float: left;
	position: absolute;
	top: 32px;
	left: 0;
	width: 85px;
	z-index: 9999;
}
#nav ul ul li {
	min-width: 105px;
}
#nav ul ul a {
	width: 105px;
}
#nav ul li:hover > ul {
	display: block;
}
/* you-are-here styles */
#nav ul li a:hover,
#nav ul li:hover > a,
#nav ul li.current_page_item > a,
#nav ul li.current_page_parent > a,
#nav ul li.current_page_ancestor > a,
#nav ul li.current-cat > a,
#nav ul li.current-menu-ancestor > a,
#nav ul li.current-menu-item > a,
#nav ul li.current-menu-parent a {
	/* background, color, etc */
}

Next, test your shiny new menu. Test with no Custom Menu (normal page navigation), with a Custom Menu enabled, and test the drop-down menus by adding submenu items.

Finally, add the custom-menu tag to your style.css file to proudly tell the world you know support a Custom Menu in your theme.

One thought on “Custom Menu Code Samples

  1. Pingback: ThemeShaper sees a redesign, refocus as the Automattic Theme Team blog | WPCandy

Comments are closed.