• Hi,
    I need to check if a page is a grandchild with a conditional IF statement to run some code on true.

    I have searched by and large the Internet, and all I found seemed very promising, but it did not work for me.

    How do you check if a page is a grandchild? For my specific purpose, I know the grandfather page’s ID, so the code does not need to generically check if a page is a grandchild of any page, it would be fine if it could check if it is a grandchild of THAT page. Whichever of the two is fine.

    Hope someone can help. Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • http://codex.wordpress.org/Function_Reference/get_post_ancestors

    <?php if( count(get_post_ancestors($post->ID)) == 2 ) echo 'this is grandchild of top page';  ?>
    <?php if( count(get_post_ancestors($post->ID)) >= 2 ) echo 'this is grandchild of some page';  ?>
    Thread Starter mariostella

    (@mariostella)

    Thanks a lot, the problem with the ancestors function is that I get “this is grandchild of top/some page” echoed in both the grandchild and the child of the grandparent page…
    My structure is very straightforward so I do not understand why the first generation is treated as the second one:
    .Page1 (grandparent)
    ..Subpage (Child)
    …Sub-Subpage (Grandchild)

    I get “this is grandchild of top/some page” in both the child and grandchild. I tried both options you suggested.

    Thanks a lot for any further help in advance..

    try and echo the post id before the code to see if it is the one of the page you are on:
    maybe also add a is_page() conditional:

    <?php
    echo $post->ID; // should be the id of the current page
    if( is_page() && count(get_post_ancestors($post->ID)) == 2 ) echo 'this is grandchild of top page';  ?>

    where in your site are you using this code?

    Thread Starter mariostella

    (@mariostella)

    I get the id of the page and the echo “this is grandchild of top page” on both the grandchild and the parent of the grandchild (i.e. the child), of course the ID changes.

    It seems as if they are both considered grandchildren…how is that possible? I am sure I have the structure correct, one is a subpage of the other, even the URL shows that…

    My functions.php file is empty, and I do not think I have plugins that should cause something like this to happen.

    Would you have any further idea? Thanks for your help so far!

    Thread Starter mariostella

    (@mariostella)

    Any ideas?

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Conditional Statement: is page a grandchild?’ is closed to new replies.