WordPress: get_post_ancestors()

In adding a few slight modifications to the photogabble theme and because a design I’m working on for someone else required it; I managed to stumble upon a ridiculously simple solution to a over complected problem, how to find the post parent when the child post is more than one level deep.

I had been using the following code to do this:

if($post->post_parent=="11"{ ... }

While this simple switch works if you are one layer deep for example Fish (ID 11) > Tropical Fish (ID 12) it wont work if your more than two layers deep such as Fish (ID 11) > Tropical Fish (ID 12) > Amazon Fish (ID 13) because $post_post_parent for Amazon Fish becomes 12 not 11. In terms of programming this is all very logical, however the solution to finding out the original post_parent otherwise known as the grandparent or great grandparent is not very well documented and it was only luck that helped me stumble upon it. The very simple function get_post_ancestors() solves this problem by effectively returning an array with every post id related to the one in which it was called as the following example shows:

$ancestors = get_post_ancestors();

$ancestors now becomes an array which we can search through the php in_array command by the following code:

in_array(11,$ancestors);

In this example if one of the $post_id’s of the current posts ancestors is 11 then the in_array function will return with true, otherwise it will return false. This then makes showing information on all sub pages (child pages) of Fish(ID 11) a simple matter of using the following code:

$ancestors = get_post_ancestors($post);
if(in_array(11,$ancestors)){
	...
}

I use this on my projects page’s to provide a link back to the projects page from the sidebar of all its children, it could also be used to show a custom header for that section of your blog or certain links from a link category relevant to that section. The usefulness of this function is never ending and should be one of many you use when writing your own templates.

4 Responses to “WordPress: get_post_ancestors()”

  1. LGR says:

    Thanks this really helped me out!

  2. Rebecca says:

    Hey- i was wondering if you could help me. I have a directory that requires certain information. The logic is like this: Directory>Org Type > Org
    On the Org.Type page I want to list something special in sidebar so currently I check to see if it’s a child of Directory and list it. When I’m on an Org. page, how do put something else in the sidebar?

    In other words, what code do i need to check for:
    if this is a child of Directory, do this…
    If is grandchild of Directory, do this..

    Thanks so much – I’d be extremely thankful for any advice you can give.

  3. Wow, you just bailed my arse out, thank you thank you thank you! :D

Leave a Reply