Below is my attempt to create a fallback function to be used as a parameter of wp_nav_menu().
What I require is for menu_default() to fire if no menu is found, but NOT when a custom menu has been created (as currently happens). Please can someone fix my code to achieve this result.
Thank you.
In header.php
<?php
wp_nav_menu( array(
'theme_location'=>'menu',
'container' =>false,
'items_wrap' =>'%3$s',
'fallback_cb' => menu_default()
)
);
?>
In functions.php
function menu_default() {
$page = get_page_by_title('Homepage');
wp_list_pages('title_li=&sort_column=menu_order&exclude='.$page->ID);
}
jazbek answers:
Hi designbuildtest,
You should put the name of your function in quotes, like this:
<?php
wp_nav_menu( array(
'theme_location'=>'menu',
'container' =>false,
'items_wrap' =>'%3$s',
'fallback_cb' => 'menu_default'
)
);
?>
The reason it's firing when a custom menu is found is because when you put the complete function call "menu_default()" as the value of fallback_cb, the function actually gets executed then.
designbuildtest comments:
Fantastic, thanks jazbek. Great to know that the fix was so simple.
Arnav Joy answers:
I Think you do not need fallback function for it just use this
<?php
if ( has_nav_menu( 'menu' ) ) {
wp_nav_menu( array(
'theme_location'=>'menu',
'container' =>false,
'items_wrap' =>'%3$s'
)
);
} else { $page = get_page_by_title('Homepage');
wp_list_pages('title_li=&sort_column=menu_order&exclude='.$page->ID);}?>
Navjot Singh answers:
You can wrap your menu function like this
if ( function_exists( 'has_nav_menu' ) && has_nav_menu( 'menu' ) ) {
wp_nav_menu( array(
'theme_location'=>'menu',
'container' =>false,
'items_wrap' =>'%3$s',
)
);
else
menu_default();