Look Through Family Tree and Find Featured Image

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 : "" );

Related posts

Leave a Reply

1 comment

  1. I don’t see anything particularly wrong with it, although I’d probably write the loop like this:

    $featuredImage = '';
    foreach ( $familyTree as $family_postid ) {
        if ( has_post_thumbnail( $family_postid ) ) {
            $featuredImage = get_the_post_thumbnail( $family_postid, 'full' );
            break;
        }
    }
    

    A bit simpler to understand and eliminates the use of the counter and boolean found variables.