Question

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.

Était-ce utile?

La solution

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top