I just built a theme that looks for a featured image on the current page, if it can’t find a featured image it will continue to look backwards through the family tree until it can find one. Then it will print it.
I wrote a little script to accomplish this but it seems inefficient. There has got to be a better way of doing it. Maybe a WP function that I missed? Here’s the code, give it a look through.
//get the ancestors
$familyTree = get_ancestors($post->ID,'page');
array_unshift( $familyTree, $post->ID ); //add the current page to the begining of the list
//loop through the family tree until you find a result or exhaust the array
$featuredImageFound = false;
$i = 0;
while (!$featuredImageFound && ($i < count($familyTree)) ) {
if(has_post_thumbnail( $familyTree[$i] )){
$featuredImage = get_the_post_thumbnail($familyTree[$i], 'full');
$featuredImageFound = true;
}
$i++;
}
// if the page has a featured image then show it
echo ( $featuredImageFound ? $featuredImage : "" );
I don’t see anything particularly wrong with it, although I’d probably write the loop like this:
A bit simpler to understand and eliminates the use of the counter and boolean found variables.