There is no need to create/update custom menus programmatically, just to do what you’re trying to do.
Just rely on the wp_nav_menu()
fallback, wp_page_menu()
, or define your own, custom callback, e.g. to output wp_list_pages()
.
Calling this:
`wp_nav_menu( array( 'theme_location' => 'main-nav' ) );`
…will, if no custom menu has been assigned to the 'main-nav'
theme location, output this:
`wp_page_menu()`.
If you want more fine-grained control, e.g. to control the menu depth explicitly, you could do the following:
wp_nav_menu( array(
'theme_location' => 'main-nav',
'depth' => 3,
'container_class' => 'nav',
'menu_id' => 'main-nav',
'fallback_cb' => 'wpse87933_main_nav_cb'
) );
…and then define your callback like so:
function wpse87933_main_nav_cb() {
?>
<div class="nav">
<ul id="main-nav">
<?php
wp_list_pages( array(
'depth' => 3,
'title_li' => ''
) );
?>
</ul>
</div>
<?php
}
You could even simplify things by using the has_nav_menu()
conditional:
if ( has_nav_menu( 'main-nav' ) ) {
wp_nav_menu( array(
'theme_location' => 'main-nav',
'depth' => 3,
'container_class' => 'nav',
'menu_id' => 'main-nav'
) );
} else {
?>
<div class="nav">
<ul id="main-nav">
<?php
wp_list_pages( array(
'depth' => 3,
'title_li' => ''
) );
?>
</ul>
</div>
<?php
}
At that point, you just need to be mindful of the CSS class differences between the 3 functions: