从文章中获取第一张图片

Avatar of Chris Coyier
Chris Coyier

假设您想使用WordPress的特色图片功能,但是有一个完整的文章存档需要花费太多时间来浏览。对于新文章,您可以指定并按预期使用该功能。对于旧文章,您只需使用在内容中找到的第一张图片作为缩略图,或者如果不存在则使用默认图片。

将此添加到functions.php中或创建一个功能插件

function catch_that_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 = "/path/to/default.png";
  }
  return $first_img;
}

要使用它,请在循环中使用此代码

if ( get_the_post_thumbnail($post_id) != '' ) {

  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';

} else {

 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo catch_that_image();
 echo '" alt="" />';
 echo '</a>';

}

我发现has_post_thumbnail不如上面的逻辑可靠。