Creating a Menu from parent page and child pages in WordPress

So on my new WordPress site I started creating pages with a template and there are children pages under it with all the same layout. In the front end all these pages need to link to each other if you are on the parent page or any of the child pages

Add the below to the functions.php file in your theme. 
function get_root_parent_id( $page_id ) {
global $wpdb;
$parent = $wpdb->get_var( “SELECT post_parent FROM $wpdb->posts WHERE post_type=’page’ AND             post_status=’publish’ AND ID = ‘$page_id'” );
if ( $parent == 0 ) {
return $page_id;
} else {
return get_root_parent_id( $parent );
}
}

So 1st we get the current page and check for children

<?php

global $post; // if outside the loop
$page_object = get_queried_object();
$page_id = get_queried_object_id(); // Get Current page id
$root_parent_id = get_root_parent_id( $page_id ); // Get Parrent page id

if($post->post_parent)
$children = wp_list_pages(“title_li=&child_of=”.$post->post_parent.”&echo=0″);
else
$children = wp_list_pages(“title_li=&child_of=”.$post->ID.”&echo=0″);
if ($children) { ?>

Now open your containing tags
<section class=”rest_sub_menu”>
<nav>
<ul class=”subpage-list”>

Check the current page title and ID
<?php $parent_title = get_the_title($post->post_parent);?>
<?php $page_id = get_the_ID($post->post_parent->ID);?>

Echo the current page link – and give the class “current_page_item” if it is the current page
<li<?php if( is_page( $page_id )) { ?> class=”current_page_item”<?php } ?>><a href=”<?php echo get_permalink($post->post_parent) ?>”><?php echo $parent_title;?></a></li>

Echo the parent page’s children
<?php echo $children; ?>

Now close all your containing tags
</ul>
</nav>
</section>
<?php } else { ?>

if no child pages are found create a spacer 
<div class=”no-menu clearfix col-md-12″></div>
<?php } ?>

Works like a charm.
Code from Stack overflow and wordpress.org

Leave a Reply

Your email address will not be published. Required fields are marked *