Mega Drop Down Menus in WordPress
I recently stumbled across this excellent tutorial for creating a nice mega dropdown menu using jQuery and standard CSS. This is an excellent choice for many sites from a usability standpoint, so I worked up some functionality to add this to a WordPress theme.
Follow the tutorial to create your menu. When you’re finished, you’ll have a nice static menu. Now we can add some magic to link the menu to WordPress pages and sub-pages. Split the code for your menu into a separate PHP file (I called mine navigation.php) and use <?php include(navigation.php); ?> in your header.php file to call it. Then, paste the following function into either your navigation.php or your functions.php file.
function print_subnav($parent_id) {
$pages = get_pages('child_of=' . $parent_id);
if(!empty($pages)) {
echo '<div class="sub">';
foreach($pages as $page) {
if($page->post_parent==$parent_id) {
echo '<ul>';
$before = '<h2>';
$after = '</h2>';
echo '<li>' . $before . '<a href="' . get_page_link($page->ID) . '">' . $page->post_title . '</a>' . $after .'</li>';
$grandchildren = get_pages('child_of=' . $page->ID);
foreach($grandchildren as $grandchild) {
echo '<li><a href="' . get_page_link($page->ID) . '#' . $grandchild->post_name . '">' . $grandchild->post_title . '</a></h2></li>';
}
}
}
echo '</div>';
}
}
Now, you simply have to add a function call under each list item, taking the place of the div.sub block:
print_subnav(121); //Use the page ID
And there you have it, automatic child page navigation!