Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 : "" );
share|improve this question
    
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

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Awesome suggestion thanks! –  BFTrick Sep 5 '12 at 17:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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