I’m trying to build a template file for my custom post type that is different for the parent, child, and child’s child post.

The best I’ve been able to find is the following code:

if( $post->post_parent !== 0 ) {
    get_template_part('content', 'child');
} else {
    get_template_part('content');
}

Only issue with this is that it only works for Parent > Child.

Is there any way to make this work for Parent > Child > Child?

1 Answer
1

Here is a basic idea:

Any page where the page parent ($post->post_parent) is 0, it means the page is a top level page. If any other value exists, the page is a child of another page. This value is the ID of the page that the specific page is a child to.

With the above information, we can calculate if the page is a child or a granchild using get_post and the returned WP_Post properties.

You can try the following: (CAVEAT: Untested)

if ($post->post_parent === 0) {

    //Do something for post parent

} else {

    $q = get_post($post->post_parent);

    if ($q->post_parent === 0) {

        //Do something for direct child

    } else {

        // Do something for grand child

    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *