Return true if parent page id matches

I'm trying to write a function (with little luck) that does a simple check against the top level parent page and re

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;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744851122a4597132.html

相关推荐

  • Return true if parent page id matches

    I'm trying to write a function (with little luck) that does a simple check against the top level parent page and re

    2天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信