When it comes to building a theme (or any WordPress project that’s going to feature custom menus), there are several options from which we can choose on how to set a default menu.
We can…
- use whatever WordPress provides,
- remove the default custom menu,
- or programmatically set a default menu
The first two are relatively easy to do (as is the third), but I’ve found that in the majority of my work, clients usually want to have a default menu of options relevant to the project at hand if the user doesn’t set one by default.
Set a Default Menu in WordPress
Again, there are a number of ways this can go but if you’re building a project for someone with a specific idea for how they want their default menu to function, then you can programmatically set the default menu options.
The nice thing is that it doesn’t require anything outside of the standard WordPress API for creating a navigation menu.
1. Call the WordPress API
Since it’s possible to wire this up using the native WordPress API, then it’s business as usual as it relates to setting up a navigation menu.
In the template file that’s going to display the menu, included at least the following:
Note that this is the bare minimum that you need in order to display a menu, but you’ll likely be specifying more options as per way the API affords.
2. Write a Function for the Menu
Next, in `functions.php` or whatever file you’re using to maintain helper functions (or however you’re separating your functions), add the following code:
In short, the code above provides a simple unordered list that displays the a link to the homepage of the blog.
Obviously, this is the bare minimum of an example. An example use case will obviously include code that’s much more specialized.
3. Set the Default Callback
Finally, we need to revisit the `wp_nav_menu` code and set a `fallback_cb` parameter:
Really simple, right?
So if a menu is not specified, then the function that we defined above will be called to provide the default menu in WordPress.
Again, this is a simple example and there are clearly other options as it relates to setting a default menu, but if you’re working with a project that has the need specialized default menu or if you want to do something unique with your theme, then this is one alternative that’s relatively easy to implement.
Leave a Reply
You must be logged in to post a comment.