WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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


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.