Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save calvez/3b86eda18ce42c9d7595f5f05fc174e1 to your computer and use it in GitHub Desktop.
Save calvez/3b86eda18ce42c9d7595f5f05fc174e1 to your computer and use it in GitHub Desktop.
Functions to add a parent count to WordPress nav menus. This is useful if you need to change nav element size based on the number of parent/top level elements.
<?php
/**
* Gets the count of the parent items in a nav menu based upon the id specified.
*
* @param string $nav_id The id of the nav item to get the parent count for.
* @return bool|int False on fail, or the count of how many parent items there are.
* @uses wp_get_nav_menu_items
*/
function count_nav_parent_items( $nav_id = null ) {
// if we don't have a nav_location, exit
if( $nav_id === null || $nav_id === '' )
return false;
// now get the nav items of the id of nav_location
$items = wp_get_nav_menu_items( $nav_id );
// if we don't have anything, exit
if( count( $items ) <= 0 )
return false;
// go through each item
$parents = array();
foreach( $items as $item ) {
// if the item's parent is 0, it's a top level, add it to an array
if( $item->menu_item_parent == 0 )
$parents[] = $item;
}
// return our count
return count( $parents );
}
/**
* Adds a class to a nav container based upon how many parent items it contains.
*
* @param array $args The array of args supplied by the filter for the nav menu.
* @return array Returns the same array passed in, just modified
* @uses get_nav_menu_locations, count_nav_parent_items
*/
function add_nav_parent_count( $args = '' ) {
// is the id in the args?
if( isset( $args[ 'menu' ]->term_id ) && $args[ 'menu' ]->term_id !== 0 ) {
// if so, set it
$menu_id = $args[ 'menu' ]->term_id;
// do we have a theme location?
} elseif( isset( $args[ 'theme_location' ] ) && $args[ 'theme_location' ] !== '' ) {
// get all the locations
$theme_nav_locations = get_nav_menu_locations();
// if we don't have any theme locations, exit
if( count( $theme_nav_locations ) <= 0 ) {
// add a theme locations not found class and exit
$args[ 'menu_class' ] = $args[ 'menu_class' ] .' parent-items-tlnf';
return $args;
}
// set the menu id
$menu_id = $theme_nav_locations[ $args[ 'theme_location' ] ];
// we have nothing
} else {
// add an id not found class and exit
$args[ 'menu_class' ] = $args[ 'menu_class' ] .' parent-items-idnf';
return $args;
}
// count the parents
$parent_count = count_nav_parent_items( $menu_id );
// if we got a count
if( $parent_count ) {
// add the class to the nav container
$args[ 'menu_class' ] = $args[ 'menu_class' ] .' parent-items-'. $parent_count;
// we didn't
} else {
// add a different class to the nav container
$args[ 'menu_class' ] = $args[ 'menu_class' ] .' parent-items-pcnf';
}
// put the array back into play
return $args;
}
add_filter( 'wp_nav_menu_args', 'add_nav_parent_count' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment