How to recursively apply a Featured image to sub pages in WordPress?

If a page is not having featured image, display the featured image of its parent page.

If again that parent is not having featured image, get it from the next higher level and so on till featured image is found or last level is reached.

Read More

Is there a solution for this in WordPress?

Related posts

Leave a Reply

2 comments

  1. You can use a recursive function like this:

      function get_featured_recursive($post) {
    
          if (has_post_thumbnail( $post->ID ) ) {
    
          return $post->ID;
    
          } else if (!has_post_thumbnail($post->ID) && $post->post_parent != 0) {
    
          $parent = get_post($post->post_parent);
    
          if (has_post_thumbnail($parent->ID)){
    
          return $parent->ID;
          }
    
          } else if(!has_post_thumbnail($parent->ID) && $parent->post_parent != 0){
    
          get_featured_recursive(get_post($parent->post_parent));
    
          }        
          else if(!has_post_thumbnail($parent->ID) && $parent->post_parent == 0 )
          { 
             return null;
          }
    
      }
    

    Then in your template use this to display the featured image:

    < ?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'); ?>
    
  2. Add the below code in your functions.php and modify as per your need:
    
    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;
    
      }
    }
    
    //In you display page:
    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'); ?>
    
    <div id="featured-bg"><img src="<?php echo$featured_image_src[0]; ?>" alt="<?php echo the_post_thumbnail_caption_from_id($featured_image_post); ?>" /> </div> </div> <div id="featured-caption">< ?php echo the_post_thumbnail_caption_from_id($featured_image_post); ?></div></div>