i’m trying to do something similar, this is what I had, but it gives me nothing:
<?php
$parent = $post->post_parent;
$grandparent = $parent->post_parent;
echo $grandparent;
?>
adding a get_post() seems to make it work:
<?php
$current = $post->ID;
$parent = $post->post_parent;
$grandparent_get = get_post($parent);
$grandparent = $grandparent_get->post_parent;
echo 'current: '.$current.'<br />';
echo 'parent: '.$parent.'<br />';
echo 'grandparent: '.$grandparent;
?>
Also, you can get the Root parent by adding this snippet to your functions.php:
function get_root_parent($page_id) {
global $wpdb;
$parent = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE post_type='page' AND ID = '$page_id'");
if ($parent == 0) return $page_id;
else return get_root_parent($parent);
}
then use this in your template:
$root_parent = get_root_parent($post->ID);
Thanks 2is3, this helped a lot when trying to get the root parent’s title.
awesome – thanks 2is3!
here’s my menu for the header – works nicely up to two levels of page depth (so children / grandchildren)
i’m sure there’s a more efficient way to do this – but this works.
<?php
$current = $post->ID;
$parent = $post->post_parent;
$haschildren = wp_list_pages("depth=1&title_li=&child_of=".$current."&echo=0");
$grandparent_get = get_post($parent);
$grandparent = $grandparent_get->post_parent;
if ($grandparent != 0) {
if ($grandparent) {
$grandchildren = wp_list_pages("depth=1&title_li=&child_of=".$grandparent."&echo=0");
}
else {
$grandchildren = wp_list_pages("depth=1&title_li=&child_of=".$grandparent."&echo=0");
}
if ($grandchildren && is_page()) { ?>
<div class="submenu">
<ul class="submenuul">
<?php echo $grandchildren; ?>
</ul>
</div>
<?php }
}
if ($parent) {
$children = wp_list_pages("depth=1&title_li=&child_of=".$parent."&echo=0");
}
else {
$children = wp_list_pages("depth=1&title_li=&child_of=".$current."&echo=0");
}
if ($children && is_page()) { ?>
<div class="submenu">
<ul class="submenuul">
<?php echo $children; ?>
</ul>
</div>
<?php }
if ($haschildren != '' && $parent != '0' && $grandparent == '0') {
$morechildren = wp_list_pages("depth=1&title_li=&child_of=".$current."&echo=0");
}
if ($morechildren && is_page()) { ?>
<div class="submenu">
<ul class="submenuul">
<?php echo $morechildren; ?>
</ul>
</div>
<?php }
?>