WordPress.org

Forums

check if current page is child or grandchild of a page (7 posts)

  1. mikuniek
    Member
    Posted 4 years ago #

    hi there, is there a simple way to check if current page is a child or grandchild of a specific page and do somenthing?

    I have a hierarchy like:

    PAGE
    subpage
    subpage2
    subpage3
    subsubpage
    subsubpage2
    subpage4

    and I'd like to have sth like:

    if (current page is child or grandchild of PAGE) {
    do sth
    }

    so that I could display a submenu for PAGE, all subpages and subsubpages

    any help would be appreciated, been looking for a solution on forums and google and found nothing :(

    basically: if current page is descendant of X then do something

  2. DigitalSquid
    Member
    Posted 4 years ago #

    Try something like this:

    $parents = get_post_ancestors($post);
    foreach($parents as $page_id){
    	if($page_id == ID of specific parent page){
    
    		// Do something
    
    		break; //Match found, no need to keep checking
    	}
    }
  3. mikuniek
    Member
    Posted 4 years ago #

    hm, looks good, will try this in a sec :)

  4. mikuniek
    Member
    Posted 4 years ago #

    gr8, works like a charm, how to add the parent page to the whole operation? This does not work:

    if(($page_id == 6) || (is_page(6))){

  5. DigitalSquid
    Member
    Posted 4 years ago #

    Yeah, WordPress doesn't seem to recognise is_page() during the foreach for some reason.

    As a work around you could put the action you want to do in your own function and call it like this:

    if(is_page('6')){
    	your_function();
    }
    else {
    $parents = get_post_ancestors($post);
    	$parents = get_post_ancestors($post);
    		foreach($parents as $page_id){
    			if($page_id == 6){
    				your_function();
    			break; //Match found, no need to keep checking
    		}
    	}
    }

    I'm sure there's a more elegant solution involving WP recognising the is_page() function though.

  6. mikuniek
    Member
    Posted 4 years ago #

    sleek, will try it, thanks for help :)

  7. liarandathief
    Member
    Posted 4 years ago #

    Try this function from the the Conditional Tags Page:

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

    it recognizes any ancestor child, grandchild, etc. Add this to your functions.php and call with is_tree('id')

Topic Closed

This topic has been closed to new replies.

About this Topic