admin管理员组

文章数量:1404769

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.

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.

Share Improve this question asked Jan 6, 2020 at 13:26 benhen31benhen31 54 bronze badges 1
  • have you try $post->post_parent; this one? – Evince Development Commented Jan 6, 2020 at 13:55
Add a comment  | 

1 Answer 1

Reset to default 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;
}

本文标签: Return true if parent page id matches