badcoder
badcoder

Reputation: 3834

How do I check if a WordPress page has another page as an ancestor?

As the title suggests, I am trying to find out if a certain page has another page as a parent or grand parent or great grand parent etc...

To check for the parent case, the following works

if (1 == $post->post_parent) {

but when checking for the ancestor

if (1 == $post->post_ancestor) {

does not seem to work.

Any ideas?

Thanks

Upvotes: 1

Views: 2123

Answers (2)

alesub
alesub

Reputation: 1492

In addition to the function provided by "ninja", also note that your condition is not correct: the "post_parent" contains the ID of the parent page, or 0 if the current page is a parent page.

So the actual condition to ask if a page has a parent is:

if($page->post_parent != 0)
    // page has a parent
else
    // page is a parent

Upvotes: 1

ninja
ninja

Reputation: 2263

There's no built in support for this, but you can use this helper function, just put it in your functions.php:

function get_ancestor() {
global $post;
if ($post->post_parent) {
    $ancestors=get_post_ancestors($post->ID);
    $root=count($ancestors)-1;
    $parent = $ancestors[$root];
} else {
    $parent = $post->ID;
}

    return $parent;
}

It will return the ID of the post that is the ancestor, so you could use it like this:

if(1 == get_ancestor()) {
    // Code here
}

Upvotes: 1

Related Questions