powered by WordPress Multibox Plugin v1.3.5
wordpressicon hanttula2 Getting Root ID from embeded pages

For quite a while now I have been using the following script to show sub navigation on WordPress Sidebars. It utilizes the built in wp_list_pages function to show parent and child relationships on a sidebar (or where ever you choose to use it for that matter).

<?php

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) { ?>  <ul> <?php echo $children; ?> </ul> <?php } ?>

I like that it is simple, and that it can be re-written to show items only if they are child pages of a specific parent, ie:

<?php
// find out what the top level page is

global $post;
if($post->post_parent) $parentPG = $post->post_parent; // page is a child
else $parentPG = $post->ID; // page has children
?>

<?php

// marketing

if($parentPG==7){

// show items if the parent id is 7
}elseif($parentPG==8){
// show items if the parent id is 8
}
?>

This works great when you only need to make it work with parent and child pages. Recently, however, I had the need to utilize this type of functionality on a project that required pages 3 levels deep (grandchildren?). After a bit of Googling, and searching through the WordPress Codex I realized that I was going to have to “roll my own” on this one. So here you go – there are probably better ways of doing this. If you know of one please let me know, but maybe this will help someone else searching for “wordpress list grandchildren”

<?php
// find out what the top level page is
global $post;
if($post->post_parent){
$parentPG = $post->post_parent; // page is a child

// check for grand children
$sql = "SELECT * FROM `".$wpdb->prefix."posts` WHERE ID=$parentPG";
$data = $wpdb->get_results($sql,ARRAY_A);

if(!empty($data[0][post_parent])) $parentPG=$data[0][post_parent];
}
else $parentPG = $post->ID; // page has children
?>

<?php

// marketing
if($parentPG==7){
// show stuff for parent 7
}elseif($parentPG==8){
// show stuff for parent 8
}
?>