1

I'm using the following code in order to get the ID of the current page's grandparent and great grandparent:

<?php
  $current = get_post($post->ID);
  $grandparent = $current->post_parent;
  $greatGrandparent = $grandparent->post_parent;
?>

<h2>$current: <?php echo $current->ID; ?></h2>
<h2>$grandparent: <?php echo $grandparent->ID; ?></h2>
<h2>$greatGrandparent: <?php echo $greatGrandparent->ID; ?></h2>

However, when I try to echo them, I only get the value of the current page:

$current: 335

$grandparent

$greatGrandparent:

I am sure to be viewing a page that actually has great/grandparent pages... can anyone see what I'm doing wrong?

1 Answer 1

3

just a small error. To get the parent and Grandparent objects, you need to get_post them also. The property "post_parent" only gives you the ID of that post, not the post_object itself.

So you change your code like this:

<?php
  $current = get_post($post->ID);
  //Conditional to be sure there is a parent
  if($current->post_parent){      
      $grandparent = get_post($current->post_parent);
      //conditional to be sure there is a greatgrandparent
      if($grandparent->post_parent){
            $greatGrandparent = get_post($grandparent->post_parent);
      }
   }
?>

<h2>$current: <?php echo $current->ID; ?></h2>
<?php if($grandparent){    ?>
    <h2>$grandparent: <?php echo $grandparent->ID; ?></h2>
    <?php if($greatGrandparent){ ?>
          <h2>$greatGrandparent: <?php echo $greatGrandparent->ID; ?></h2>
  <?php } } ?>

And everything is fine!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy