Error “Trying to get property of non-object” with Custom Walker for wp_nav_menu

I get this error when there are no menus defined or no menus set for the location at Appearance->Menus. When that occurs wp_nav_menu uses a page walker fallback.

  1. The fallback (default) for wp_nav_menu is wp_walker_page
  2. which uses wp_page_menu
  3. which uses wp_list_pages
  4. which uses walk_page_tree
  5. which uses Walker_Page not Walker_Nav_Menu.

And apparently the two walkers are not compatible. I don’t know why it doesn’t fail gracefully. That seems like a bug to me.

With a menu set at wp-admin->Appearance->Menus, your code works.

You can avoid the error by checking to see that there is a menu assigned to the location before trying to use the location.

$locations = get_nav_menu_locations();
if (0 !== $locations['main-nav']) {
  wp_nav_menu( array(
      'theme_location' => 'main-nav',
      'walker'         => new Walker_Nav_Menu_With_Aria,
  ) );
}

Or, if you’d prefer less antihistamine addled code ( thanks @Rarst ):

if (has_nav_menu('primary')) {
  wp_nav_menu( array(
      'theme_location' => 'primary',
      'walker'         => new Walker_Nav_Menu_With_Aria,
  ) );
}

Leave a Comment

error code: 523