Justin Tadlock

How to widgetize your page menu in WordPress

We all feel the pain of having to customize our page menus for pretty much any WordPress theme. Sure, there are plugins that give you control over this, but it shouldn’t be so hard.

There are several methods that people have been trying to overcome this one frustrating thing with WordPress, but the method I’m describing here is easy and requires little coding.

In this tutorial, I’m going to show you how to completely widgetize your menu. I’m actually using this very method in my upcoming redesign of Theme Hybrid, and I’m the kind of person that feels more than comfortable diddling with code.

The setup

I’m going to make an assumption that your theme has been updated to use the latest WordPress functions — themes like Hybrid and Thematic make use of this.

Your theme needs to use the wp_page_menu() function to add its page menu. While this isn’t a requirement to widgetize your menu, I’ll be using it here.

Open your theme’s functions.php file and drop this code in:

<?php

register_sidebar( array(
    'name' => 'Page Menu',
    'id' => 'page-menu',
    'before_widget' => '<div id="page-nav">',
    'after_widget' => '</div>',
    'before_title' => false,
    'after_title' => false
) );

add_filter( 'wp_page_menu', 'my_page_menu' );

function my_page_menu( $menu ) {
    dynamic_sidebar( 'page-menu' );
}

?>

That’s all the code you must add to your theme. Your page menu is now completely widgetized.

Adding widgets to your page menu

Of course, you’ll want to add a list of pages now. Head over to the Widgets page in your WordPress admin. Select the Page Menu widget area.

From this point, you have several options:

  • Make an unordered list in the text widget.
  • Use the Widgets Reloaded plugin for complete control over pages.
  • Use the Hybrid theme, which has a cool pages widget.
  • Find another widget that allows greater control over pages.

A few notes about this method

If your theme does not use the wp_page_menu() function, replace your theme’s menu code with this:

<?php wp_page_menu(); ?>

I think it goes without saying, but just in case — don’t add a title to your widget. That’ll likely screw up your page menu. You might also need to change the ID of page-nav to match your theme’s CSS.

If you are using my Hybrid theme, I’ve put up a tutorial on the support forums on how to use the Superfish JavaScript for drop-downs with this technique.