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;

// if the page has a featured image then show it
echo ( $featuredImageFound ? $featuredImage : "" );
  • if it works (I assume it does), then that's more something for codereview or chat. – kaiser Sep 5 '12 at 15:06
  • I didn't even know about codereview. Thanks! – BFTrick Sep 5 '12 at 17:45

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' );

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

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.