WordPress – Recursively display a featured image & caption on child pages

While working on and searching for a solution to recursively display a WordPress page’s featured image and caption with the ability to be overridden if a different image is uploaded to a ┬ásub page; my search result yielded a couple frantic posts that were never replied to and my attempts were close but no cigar. This is something we do often in our Java based CMS, NuContent so it made sense to make it work for us in WordPress. One of our trusty software engineers took my half working code and did their command line magic to get it to work correctly (actually just some nano or vim, they make it look magical from afar). Within about 12 minutes plus a RedBull break, it was made it into a masterpiece that did exactly what I wanted it to do.

To reiterate what we wanted to accomplish:

  1. We wanted the featured image and caption to be outputted on a 1st level page and all child pages below down to 3rd or 4th level even.
  2. If we uploaded a different image and caption on a 2nd or 3rd level page, we wanted it to override the 1st level image on that page and the child pages of it.

In your theme’s functions.php file, use the following and modify as needed:

// recurively looks for featured images
function get_featured_recursive($post) {
  if (has_post_thumbnail( $post->ID ) ) {
    return $post->ID;
  } else if ($post->post_parent != 0) {
    return get_featured_recursive(get_post($post->post_parent));
  } else {
    return null;
//Find the caption
function the_post_thumbnail_caption_from_id($post_id) {
  $thumbnail_id    = get_post_thumbnail_id($post_id);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
  if ($thumbnail_image && isset($thumbnail_image[0])) {
    echo ($thumbnail_image[0]->post_excerpt);

And on the template you’re modifying (page.php for me), the image gets displayed and the caption gets absolute positioned overtop of the image with my CSS which is not shown

//Make sure spacing in the <!--?php tags is corrected.
//Give me the image
<div id="featured">

< ?php $featured_image_post = get_featured_recursive($post); if ($featured_image_post != null) : $featured_image_src = wp_get_attachment_image_src(get_post_thumbnail_id($featured_image_post), 'single-post-thumbnail'); ?>

Please let us know if you have any improvements to this or any questions. I’ll keep updating it with improvements in the future.

About the Author

Greg is a front-end web developer / Production Manager at NuRelm. Should you hire us to do a website, you will more than likely meet him. He likes (most) things related to internet and loves sharing his knowledge. When not working or researching, he is devoted to long distance cycling & endurance challenges.

Author Profile: