Cameron
Cameron

Reputation: 28783

WordPress help with checking if parent page

I have this function that checks if a page is the parent:

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
        global $post;         // load details about this page
        if(is_page()&&($post->post_parent==$pid||is_page($pid)))
               return true;   // we're at the page or at a sub page
        else
               return false;  // we're elsewhere
};

and use it like so to show a menu:

<?php if (is_tree(6) || is_page(6)) { menu code here } ?>

However it only works for the immediate sub-pages and not the sub sub pages e.g.

domain.com/page1.0/page1.1/page1.1.1/

If page1.0 has an id of 6, the menu will appear on page 1.0 and 1.1 but not 1.1.1

How can I modify the code so that the tree function works for ANYTHING that is below the page ID specified and NOT just the IMMEDIATE sub-pages.

Thanks

Upvotes: 0

Views: 1169

Answers (2)

user7675
user7675

Reputation:

Use get_post_ancestors():

function is_tree( $pid ) {
    if ( is_page() ) {
        return ( get_the_ID() == $pid || in_array( $pid, get_post_ancestors( get_the_ID() ) ) );
    }

    return false;
}

Upvotes: 1

Cameron
Cameron

Reputation: 28783

This works:

function is_tree( $pid ) {
global $post;         // load details about this page
if ( is_page() ) {
    return ( $post->ID == $pid || in_array( $pid, get_post_ancestors( $post->ID ) ) );
}

return false;

};

Upvotes: 0

Related Questions