WordPress : Creating a Second Level Navigation Only Menu

This is the last post based on my mini WordPress project.  This post will show you how to create a custom WordPress menu that will only show the first page in the tree and the second levels as children, regardless of where you are in the page.

The first thing the code does is get the current page and recurse up the tree until it finds the first page in the tree. Once it has the first page, it writes an anchor in a ul.  The next step is querying WordPress for all the page ID’s that have a parent Id of the first page.  Finally it iterates through these ID’s and displays them in a child ul.

$current = $post;	 	 
while($current->post_parent) {	 	 
$current = get_post($current->post_parent);	 	 
$id = $current->ID;	 	 
$toplink = '<a href='. get_permalink($id) .' class="active">'. get_the_title($post->post_parent) .'</a>';	 	 
$childItems = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent IN ($id) AND $wpdb->posts.post_type = 'page' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.ID ASC");	 	 
$childItemIds = implode($childItems,', ');	 	 
if (count($childItems) != 0)	 	 
wp_list_pages('include=' . $childItemIds . '&title_li='. $toplink .'');	 	 
echo '<ul>'. $toplink .'</ul>';	 	 

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts