• Hi, I want to show the parent page of a page in the sidebar. I tried the following, but it simply shows shows what data type is.

    global $post;
    $parents = get_post_ancestors( $post->ID );
    echo $parents;

    output is:

    Array

    What is the correct usage of this?

    Thank you!

Viewing 7 replies - 1 through 7 (of 7 total)
  • to see an array use:

    print_r($parents);

    from there, you’ll find that you’ll have to do something similar to:

    echo "<a href='".get_permalink($parents[0]->ID)."'>{$parents[0]->post_title}</a>";
    Thread Starter mad_griffith

    (@niccolomineo)

    Thanks David, but adding

    print_r($parents)

    only outputs

    Array ()

    p.s. I am using Enhanced text sidebar widget to embed the PHP code

    if the array’s empty then there’s no parent for that post.

    if you’re certain there’s a parent, and the parent page is set via the “Page Attribute” field (and not the WordPress Menu interface) then I will take a guess and say that the Widget fires before $post is set/defined.. in which case you will need to find another way to find out what the current page ID is.

    ((you can check if $post is set by simply doing: echo $post->ID should return a number))

    Thread Starter mad_griffith

    (@niccolomineo)

    Yes, I made sure it was set through the page attribute before starting playing with this. Then I have find another way. Thanks a lot.

    Thread Starter mad_griffith

    (@niccolomineo)

    I tried echoing the get_the_ID() function and it works.

    But

    <?php
    global $post;
    $parents = get_post_ancestors( get_the_ID() );
    print_r($parents);
    ?>

    prints

    Array ( [0] => 30 )

    I’d need to loop then, I believe.

    https://codex.www.ads-software.com/Function_Reference/get_post_ancestors

    Return Array of IDs or empty if no ancestors are found

    so

    <?
    
    $parents = get_post_ancestors( get_the_ID() );
    
    foreach ($parents as $a_parent_ID)
    {
         $parent = get_post($a_parent_ID);
         echo "{$parent->post_title}<br />";
    }
    
    ?>
    Thread Starter mad_griffith

    (@niccolomineo)

    Thanks a lot, I tried to loop but was missing the get_post() bit.

    Now I will try to add a link to it and then I will delve into echoing the child pages.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘get_post_ancestors ? how does it work?’ is closed to new replies.