How to recursively apply a selected image to subpages in Wordpress?

If the page does not have a highlighted image, display the displayed image of its parent page.

If this parent does not have a highlighted image, get it from the next higher level and so on until a recognized image appears or the last level is reached.

Is there a solution for this in Wordpress?

+4
source share
2 answers

You can use the recursive function as follows:

  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 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'); ?>
+1
source
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>
0
source

Source: https://habr.com/ru/post/1538012/


All Articles