Display Subnav If Page has Children

Create two functions within functions.php. One will control the “if(has)” parameter that will be called within the page template, and one will contain the data that we want to display:

function has_submenu(){

	global $post;

	if (is_page( )) {
	$page = $post->ID;
		if ($post->post_parent) {
		  
		   $page = $post->post_parent;
		}
		
		$children=wp_list_pages( 'echo=0&child_of=' . $page . '&title_li=' );
		if ($children) {
		  
			$output = wp_list_pages ('echo=0&child_of=' . $page . '&title_li=');
	
		}
	}
	
	return $children; // return the argument, or nothing will exist
}


function display_submenu($get_count  = false) {
	
	global $post;

	if (is_page( )) {
	$page = $post->ID;
		if ($post->post_parent) {
		  
		   $page = $post->post_parent;
		}
		
		$children=wp_list_pages( 'echo=0&child_of=' . $page . '&title_li=' );
		if ($children) {
		  
			$output = wp_list_pages ('echo=0&child_of=' . $page . '&title_li=');
	
		}
	}
	
	if($output) {
	
		echo '<div id="submenu_container"><div class="sub_menu">';
		
		echo '<ul>';
		
		echo $output;
		
		echo '</ul></div></div>';
	
	}
}


Within the page template add the class to the div where you would like the content to display inline:

<div id="content" class="<?php if(has_submenu()) { echo 'with_submenu'; } ?>">

Above or below this div, add the function that will display the content of the submenu (the second function that we created in functions.php:

<?php if(has_submenu()) {
	echo display_submenu();
} ?>

Apply CSS to the new elements:

#content.with_submenu {
	width: 70%;
}

#submenu_container {
	width: 15%;
	display: inline-block;
	vertical-align: top;
	background: #d6841b;
	padding: 2%;
	margin: 0 1%;
}

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.