Php 如何在Wordpress中递归地将特色图像应用于子页面?

Php 如何在Wordpress中递归地将特色图像应用于子页面?,php,wordpress,Php,Wordpress,如果页面没有特征图像,则显示其父页面的特征图像 如果父级没有特征图像,则从下一个更高级别获取,依此类推,直到找到特征图像或达到最后一个级别 Wordpress中是否有解决方案?在functions.php中添加以下代码,并根据需要进行修改: Add the below code in your functions.php and modify as per your need: function get_featured_recursive($post) { if (has_post_t

如果页面没有特征图像,则显示其父页面的特征图像

如果父级没有特征图像,则从下一个更高级别获取,依此类推,直到找到特征图像或达到最后一个级别

Wordpress中是否有解决方案?

在functions.php中添加以下代码,并根据需要进行修改:
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>
函数get\u featured\u recursive($post){ 如果(有帖子缩略图($post->ID)){ 返回$post->ID; }else if($post->post\u parent!=0){ 返回get_recursive(get_post($post->post_parent)); }否则{ 返回null; } } //在您的显示页面中: div id=“特色”> <?php$featured\u image\u post=get\u featured\u recursive($post);如果($featured\u image\u post!=null):$featured\u image\u src=wp\u get\u attachment\u image\u src(get\u post\u thumbnail\u id($featured\u image\u post),'single post thumbnail');?> “alt=”“/><?php从_id($featured _image _post);?>
您可以使用如下递归函数:

  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;
      }

  }
然后在模板中使用此选项显示特色图像:

< ?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'); ?>
<?php$featured\u image\u post=get\u featured\u recursive($post);
如果($featured\u image\u post!=null):$featured\u image\u src=wp\u get\u attachment\u image\u src(get\u post\u thumbnail\u id($featured\u image\u post),'single post thumbnail');?>