WordPress自动获取文章内第一张图片做为缩略图

如果你的站点文章数量很多,那么每一篇文章都要手动设置缩略图必然会是个繁杂的步骤,之前我们分享过一篇《图片做为缩略图。

这将大大减少我们的工作量,的确是一个很好的小功能,喜欢的朋友可以自己试试。

//自动获取文章内第一张图片做为缩略图
function catch_first_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)){ //Defines a default image
    $first_img = \\\\\\\"/wp-content/themes/um/img/default.png\\\\\\\";
  }
  return $first_img;
}

使用方法

将上面代码添加到自己主题的functions.php文件。

<?php echo catch_first_image() ?>

2、将上面代码添加到需要获取缩略图的文章循环中即可。