One of the relatively new things I like most about WordPress is the custom menus feature, which was first introduced in version 3.0. For pretty much all of my latest projects, I use the custom menu feature exclusively when it comes to menus. Many themes have menu locations that you can create your own menu and then plug it in. For instance, my favorite theme, Genesis by StudioPress, offers 2 locations that I can make custom menus.
But for this one project I’m working on, I wanted to make a menu that can also appear in my sidebar as a widget. Hmmmm…
Sure, once I head over to the widgets area, I notice that Genesis has Genesis – Page Navigation Menu, but that’s only good if A.) You are building a child-theme from Genesis and/or B.) You are fine with just picking and choosing the pages you created in WordPress. One of the great features of Custom Menus is that you can link to pages/assets outside of your WordPress installation. So, let’s look at how we can bring widgets and custom menus together for some awesome development flexibility.
First, go to Menus under Appearance in the WordPress admin area. Once there, create a menu called Widget Navigation and add a few pages, links, or whatever to fill out the menu.
Once you have your navigation complete, save it and open your theme’s functions.php file and add this bit of code:
function sub_menu_widget() {
wp_nav_menu( array('menu' => 'Sub Navigation' ));
}
wp_register_sidebar_widget(
'menu_widget_1',
'Submenu Widget',
'sub_menu_widget',
array(
'description' => 'Custom widget menu'
)
);
Okay, let’s take a look at what’s going on here. We created a function called menu_widget, which when called outputs the Custom Menu we created called Widget Navigation (if you used a different name here, be sure to change the code to reflect the name you chose). In the second part of the code we register the widget. The first argument we pass is the widget ID I called menu_widget_1. This is used internally by WordPress to refer to your widget; it can basically be anything as log as it’s unique. The second argument is the name of your widget, which I called Widget Navigation. The third is our callback function which we went over already, and lastly, the fourth is an optional array. For this one, I simply defined the description. You don’t even need to include this, but I like having a description…
Once all this is in place and saved, head over to Appearance and then to Widgets. If you did everything correctly, you will find your widget under Available Widgets. Now just drag it over to one of your sidebars and you are good to go! If you have any questions, comments, or find any errors in my code, please let me know in the comments.