php - 如何递归地将特色图片应用于 Wordpress 中的子页面?

标签 php wordpress

如果页面没有特色图片,则显示其父页面的特色图片。

如果父级再次没有特色图片,则从下一个更高级别获取它,依此类推,直到找到特色图片或达到最后一个级别。

Wordpress 中是否有针对此问题的解决方案?

最佳答案

你可以像这样使用递归函数:

  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 - 如何递归地将特色图片应用于 Wordpress 中的子页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23285978/

相关文章:

php - HTML 数据经过十六进制处理后超出字段长度

javascript - 当按下提交按钮而不是页面刷新时重新加载php脚本

php - php中如何统计上传文件的数量

php - 显示 MYSQL 结果时出现问题

css - 第一页上未显示外部字体

php - 在循环内增加数组长度,使其与其他数组大小相同

wordpress - 隐藏与 Woocommerce 不匹配的变体

php - 不安全的内容。如何在模板中全局更改谷歌字体 url

javascript - 如何结合 .load 向 div 添加缓动

PHP 安装似乎缺少 WordPress 所需的 MySQL 扩展?