Menu Close

How To Set a Fallback for Your WordPress Menu

default

WorddPress 3 has been out for a long time now yet there are still TONS of people who have no idea how to use the new WordPress custom menu admin. For this reason as a theme developer it’s important to show a fallback for your menu so your buyers/theme users don’t think that something is messed up with your theme. Below I will show you what I think is the ideal solution, creating a custom fallback with a link to “wp-admin/nav-menus.php” so when the user installs the theme they can click on the link and go set up their menu right away.

Step 1: Create The Fallback Function

First thing we are going to do is add a new function to your functions.php file (or whatever file you use to register your custom menu areas). Add the following code, preferably right after the register_nav_menu function for better usability. This function will grab the new file that you will create in step 2 with the code for your default/fallback menu.

// Menu Fallback
function wpex_default_menu() {
    get_template_part( 'template-parts/default-menu.php' );
}

Step 2: Set Up Your Default/Fallback Menu

Now you need to create the file that the function added previously will grab and display when a menu isn’t defined in the WP admin for your menu area.

a. Create a new folder called “template-parts” in your theme folder if one doesn’t exist already

b. Create a new file called default-menu.php

3. Insert your code for your fallback menu in this file (make sure it matches the code used on your site so it looks nice). Below is a basic example:

<ul>                  
    <li><a href="<?php echo admin_url('nav-menus.php'); ?>"><?php esc_html_e( 'Set Up Your Menu', 'text_domain' ); ?></a></li>
</ul>

Step 3: Call Your Fallback function in your menu

Now you’ll want to go back to your “wp_nav_menu” function and add your fallback as a part of the array and call the function  you created in step one, such as the example below:

<?php
//define main navigation
wp_nav_menu( array(
    'theme_location' => 'main',
    'fallback_cb'    => 'wpex_default_menu',
) ); ?>

View Source
Posted in WordPress