Conditional statement for parent, child and grandchild pages

I’m trying to figure out how to set up a conditional statement to check if the parent, child or grandchild is being displayed. This is what I’ve got so far:

<?php 

if ( is_page( 'about' ) || '29' == $post->post_parent ) {
    //Start of the custom code...
    while(has_sub_field('site_slideshows','option')):
    ?> <!-- Closing the PHP tag -->

        <div class="slideshow-slide" style="background-image:url(<?php the_sub_field('site_slideshows_slide_image'); ?>)">
            <div class="block-text" style="color: <?php the_sub_field('site_slideshows_slide_text_colour'); ?>;"><?php the_sub_field('site_slideshows_slide_text'); ?></div>
        </div>

    <?php //Opening the PHP tag again
    endwhile;

} elseif ( is_page( 'contact' ) || '31' == $post->post_parent ) {
    //Start of the custom code...
    while(has_sub_field('two_site_slideshows','option')):
    ?> <!-- Closing the PHP tag -->

        <div class="slideshow-slide" style="background-image:url(<?php the_sub_field('two_site_slideshows_slide_image'); ?>)">
            <div class="block-text" style="color: <?php the_sub_field('two_site_slide_text_colour'); ?>;"><?php the_sub_field('two_site_slideshows_slide_text'); ?></div>
        </div>

    <?php //Opening the PHP tag again
    endwhile;

}
?>

This will successfully check for the parent and child page, e.g. the about page and all the children of the about page, but how would I adjust these statements to include grandchild pages also? Any suggestions would be greatly appreciated.

Related posts

1 comment

  1. Use get_post_ancestors( $post ). It returns an array of post IDs. The parent ID is the first entry, the grand parent the second and so on.

    $ancestors = get_post_ancestors( $post );
    
    if ( is_page( 'about' ) || in_array( '29', $ancestors ) )
    {
        echo "This is About or one of its descendants";
    }
    elseif ( is_page( 'contact' ) || in_array( '31', $ancestors ) )
    {
        echo "This is Contact or one of its descendants";
    }
    

Comments are closed.