Wordpress - 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.
- The fallback (default) for
wp_nav_menu
iswp_walker_page
- which uses
wp_page_menu
- which uses
wp_list_pages
- which uses
walk_page_tree
- which uses
Walker_Page
notWalker_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,
) );
}