• 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

Viewing 6 replies - 1 through 6 (of 6 total)
  • DigitalSquid

    (@twelvefootsnowman)

    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
    	}
    }
    Thread Starter mikuniek

    (@mikuniek)

    hm, looks good, will try this in a sec ??

    Thread Starter mikuniek

    (@mikuniek)

    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))){

    DigitalSquid

    (@twelvefootsnowman)

    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.

    Thread Starter mikuniek

    (@mikuniek)

    sleek, will try it, thanks for help ??

    liarandathief

    (@liarandathief)

    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’)

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘check if current page is child or grandchild of a page’ is closed to new replies.