Posted on

Add parent menu class

Chip Bennett gave an excellent code snippet in theme reviewers email list. It adds menu-item-parent class to every parent menu item.

function my_add_menu_parent_class( $items ) {

$parents = array();

foreach ( $items as $item ) {

if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {

$parents[] = $item->menu_item_parent;

}

}

foreach ( $items as $item ) {

if ( in_array( $item->ID, $parents ) ) {

$item->classes[] = 'menu-item-parent';

}

}

return $items;

}

add_filter( 'wp_nav_menu_objects', 'my_add_menu_parent_class' );

So what’s the big deal? Well you could use it for Drop Down Menu Indicator for example and with this you don’t’ need to do it jQuery mumbo jubmo. Here is an example how you could add drop down menu indicator using Font Awesome icon font.

#menu-primary .menu-item-parent > a:after {
content: "\f105";
float: right;
font-family: 'FontAwesome';
padding-left: 8px;
padding-left: 0.5rem;
}

Here is another example. Which one you prefer?

Edit: Justin Tadlock suggested in his forums that you could do this using pure CSS. Nice.

#menu-primary li > a::after {
content: "\f105";
float: right;
font-family: 'FontAwesome';
padding-left: 8px;
padding-left: 0.5rem;
}

#menu-primary li > a:only-child::after {
content: '';
display: none;
}

Note. only-child selector is supported in all major browsers, except IE8 and earlier.