WordPress.org

Ready to get started?Download WordPress

Forums

Conditional Statement: is page a grandchild? (6 posts)

  1. mariostella
    Member
    Posted 3 years ago #

    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

  2. alchymyth
    Forum Moderator
    Posted 3 years ago #

    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';  ?>
  3. mariostella
    Member
    Posted 3 years ago #

    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..

  4. alchymyth
    Forum Moderator
    Posted 3 years ago #

    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?

  5. mariostella
    Member
    Posted 3 years ago #

    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!

  6. mariostella
    Member
    Posted 3 years ago #

    Any ideas?

Topic Closed

This topic has been closed to new replies.

About this Topic