0

I'm trying to write a function (with little luck) that does a simple check against the top level parent page and returns true if the ID matches a supplied ID number.

For example; If I'm on page Firefly>Kaylee>Outfits, I will supply my function the ID of the page Firefly (perhaps '29'). The function would return True.

If I'm on the page Fringe>Josh>Outfits the same function call would return False because the top level parent (Fringe) does not have the ID of 29.

I have seen examples on here that could do this with the direct parent, but they don't work if the page the function is being called from is more than one level deep.

How can this be written in a way that it will always find the top most parent no matter how many levels deep the page is that the function is called from, and return True or False?

Many thanks, Ben.

0

You can get all ancestors with get_post_ancestors. The root ancestor is the last element of the returned array. Here is the function that checks a target page id against the root ancestor of current page:

function check_page_parent( $target_page_id ) {
    $ancestors = get_post_ancestors( get_the_ID() );

    if ( $ancestors ) {
        $top_most_parent_index = count( $ancestors ) - 1;
        $top_most_parent_id    = $ancestors[ $top_most_parent_index ];

        return ( $top_most_parent_id == $target_page_id);
    }

    return false;
}
|improve this answer|||||
  • Thanks for the reply, I missed the notification on this! Looks great - it should auto detect the $current_page_id rather than need it to be specified. I only want to have to pass the target page ID to the function. Can it do that? – benhen31 Jan 7 at 22:54
  • @benhen31 Yes. But there should be a global post. I Edited My answer. – Had1z Jan 8 at 6:23
  • Absolutely awesome, this works exactly as I was trying to do. Thanks for the great answer! – benhen31 Jan 8 at 14:52
  • @benhen31 You're welcome :) – Had1z Jan 8 at 15:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.