I'm developing a wordpress theme with nested submenus. I need to make the elements with no children visually different from the ones that have children. Right now I have this menu, but that could change:
A a1 a2 B b1 b2 C
As you can see, A and B have children. C doesn't - I need it to be different in the CSS level.
Ideally, I would like to have a has-children
class in A and B, but not in C.
So far I've managed to create a "Menu Walker" PHP class that I can instantiate and pass to wp_nav_menu . Its constructor looks like this:
class My_Walker_Nav_Menu extends Walker_Nav_Menu { function start_el(&$output, $item, $depth, $args) { ... if(??? $item has children???) { // I know what to do here } } }
So, how do I tell whether $item
has children, or is a leaf?
EDIT: this question was answered by someone called "keesiemeijer" in the Wordpress forums. I'm leaving this bounty expired just in case he wants to reclaim it. Otherwise, I'll be marking my own answer as valid.
In WordPress and later you can create and name the menu. You can get all menu items using this code: $menu = wp_get_nav_menu_items('menu_name'); print_r($menu); Sometimes, you will need to get only the child menu items for specified parent item.
You can just change it in wordpress file. location : www/project_name/wp-includes/nav-menu-template. php. open this file and at line number 49, change the name of sub-menu class with your custom class.
Add this to functions.php
it will add the 'dropdown' class to parents
New way beter for performance
function menu_set_dropdown( $sorted_menu_items, $args ) { $last_top = 0; foreach ( $sorted_menu_items as $key => $obj ) { // it is a top lv item? if ( 0 == $obj->menu_item_parent ) { // set the key of the parent $last_top = $key; } else { $sorted_menu_items[$last_top]->classes['dropdown'] = 'dropdown'; } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'menu_set_dropdown', 10, 2 );
Old: intensive on the DB
add_filter( 'nav_menu_css_class', 'check_for_submenu', 10, 2); function check_for_submenu($classes, $item) { global $wpdb; $has_children = $wpdb->get_var("SELECT COUNT(meta_id) FROM wp_postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='".$item->ID."'"); if ($has_children > 0) array_push($classes,'dropdown'); // add the class dropdown to the current list return $classes; }
Simple you use this way:
Explain: I create menu with "walker":
$walker = new Nav_Walker; wp_nav_menu(array( 'container'=>'nav', 'container_class'=>'menu', 'menu_class'=>'list-unstyled list-inline', 'walker'=>$walker ));
Class Walker:
class Nav_Walker extends Walker_Nav_Menu { public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { if($args->walker->has_children) { //code... } } }
We have object 'walker', you can var_dump($args) to see more things. I'm using for my project !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With