WordPress get all subpages of current page’s parent page

Following code will display all the subpages of same parent page. also displays the subpages of current page if it is not a subpage.

<?php
// Get Parent of current page....
$parents_id = $wpdb->get_row("SELECT post_parent	FROM $wpdb->posts WHERE id = ".$post->ID."	AND post_type = 'page' ORDER BY menu_order", 'OBJECT');	

if($parents_id->post_parent >0) // If this page have parent
{
	// Get all the subpages of the parent page.
	$child_pages = $wpdb->get_results("SELECT *	FROM $wpdb->posts WHERE post_parent = ".$parents_id->post_parent."	AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
if(count($child_pages))// If count is greater than 0
{
?>
<ul>
<li><strong><?php echo get_the_title( $parents_id->post_parent);?></strong></li>
<?php if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>
<li><a href="<?php echo $pageChild->guid; ?>" rel="bookmark" title="<?php echo $pageChild->post_title; ?>"><?php echo $pageChild->post_title; ?></a></li>
<?php endforeach; endif;?>
</ul>
<?php
}
}
else
{
	//If the current page is a top level page and it is not a subpage.
	//Get the subpages of the current page
	$child_pages = $wpdb->get_results("SELECT *	FROM $wpdb->posts WHERE post_parent = ".$post->ID."	AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
	if(count($child_pages))
{
?>
<ul>
<li><strong><?php echo get_the_title( $post->ID);?></strong></li>
<?php if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>
<li><a href="<?php echo $pageChild->guid; ?>" rel="bookmark" title="<?php echo $pageChild->post_title; ?>"><?php echo $pageChild->post_title; ?></a></li>
<?php endforeach; endif;?>
</ul>
<?php
}
}
?>

Leave a Reply