1

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?

0

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

    }

}
  • Any feedback on this? – Pieter Goosen Feb 9 '15 at 12:27
  • Apologies for the belated reply. Works like a charm! – Rob Jul 25 '15 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.