RSS

How To Find If WordPress Menu Item Has Children

05 Sep

WordPress developers write custom walker class to customize wordpress menu. There arise some cases where we need to find if a menu item has children or sub menu.

Here is a situation. We have a multilevel navigation menu. If a menu item has sub menu associated, we need to show an icon next to menu item. This helps users to know that there is a sub menu.

To do this, we need to add a function to custom walker class. It looks like this:

1
2
3
4
5
6
7
8
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output )
{
    $id_field = $this->db_fields[‘id’];
    if ( is_object( $args[0] ) ) {
        $args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
    }
    return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}

 

Now you can test for has_children inside your start_el() function. Here is a helper code:

1
2
3
4
5
6
7
8
9
10
class Walker_Primary_Menu extends Walker_Nav_Menu {
    // add main/sub classes to li’s and links
    function start_el( &$output, $item, $depth, $args ) {
        // …
        if ( $args->has_children ) {
            // do something
        }
        // …
    }
}

 

Advertisements
 
Leave a comment

Posted by on September 5, 2013 in Wordpress

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: