从相关帖子(wp)抓住第一张图片

时间:2014-01-05 16:16:47

标签: php wordpress post wordpress-plugin thumbnails

我为相关帖子中的show缩略图编写此代码。如果相关帖子没有缩略图,则应显示其内容中的第一张图片:

     $output .= "<a href=\"".get_permalink($related_post->ID)."\">";
          if(get_the_post_thumbnail($related_post->ID)) {
              $output .= get_the_post_thumbnail($related_post->ID, $options['thumbnail_size']);
          } else {
              $output .= catch_image( $related_post->ID );
          }
     $output .= "</a>";

并且在function.php中我有这个功能:

   function catch_image() {
       global $post, $posts;
       $first_img = '';
       ob_start();
       ob_end_clean();
       $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
       $first_img = $matches[1][0];

       if(empty($first_img)) {
            $first_img = "url for noimage.jpg";
       }

   return $first_img;
   }

但这只是给了我这篇文章的第一张图片,而不是相关的帖子。我怎样才能获取我需要的内容?

1 个答案:

答案 0 :(得分:1)

尝试使用此功能:

 function catch_image($post_id) {

   $first_img = '';
   ob_start();
   ob_end_clean();
   $related_post = get_post($post_id);
   $content = $related_post->post_content;
   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
   $first_img = $matches[1][0];

   if(empty($first_img)) {
        $first_img = "url for noimage.jpg";
   }

   return $first_img;
 }