Hello,
I am trying to get an image field from a grandparent page. I have three layers of hierarchy in my site structure and I can only get back 1.
Example site structure:
Parent Page
Grandchild
Great Grandchild
I have had some success with the following:
if ( 0 == $post->post_parent ) {
the_title();
} else {
$parents = get_post_ancestors( $post->ID );
echo apply_filters( "the_title", get_the_title( end ( $parents ) ) );
}
But I would like to get a more consistent result. Could you suggest an approach please?
Thank you,
Marc
The only thing I could see you adding is limiting it to the Grandparent at the most:
if ( 0 == $post->post_parent ) {
the_title();
} else {
$parents = get_post_ancestors( $post->ID );
$parents = array_slice($parents, 0, 2);
echo apply_filters( "the_title", get_the_title( end ( $parents ) ) );
}
I think that should give you either the parent or the grandparent, but not further back. If you want to limit it only to the grandparent then you’d need to make sure that the slice has a count of at least 2.