November 9, 2016 · wordpress menu has_children

Wordpress Custom Menu Walker - Check if an item has children

Recently we've discussed menu parent items in a Wordpress Menu Walker. Today we will have a quick look at their counterparts: Children.

Unfortunately we can't use the $WP_POST property has_children to determine if a menu item actually has children. When researching this topic I've seen many solutions on stackoverflow and other blog posts. Most of them seemed rather complicated for such an arguably easy task.

After having a look at the Wordpress source code I've found an interesting method: $item->classes. Each menu item has such a property that is automatically populated before being passed to an overriding custom walker. One of those classes will tell us if that particular item has children: menu-item-has-children.

Direct access to the current item is available when overriding the start_el and end_el methods of Walker_Nav_Menu. This allows us statements like:

    if(in_array('menu-item-has-children', $item->classes)){...}

With such constructs we can handle cases for items that have children. Unfortunately this won't give us actual access to those children, which is far from ideal.
Still, if you just need to now if an item has children or not, this is a quick and simple solution.

On a side note: While this solution works nicely, I'm not fully convinced of checking for a class name (read: magic string). If somebody knows of a better solution that's not too convoluted please let me know.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus