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

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

如果你的站点文章数量很多,那么每一篇文章都要手动设置缩略图必然会是个繁杂的步骤,之前我们分享过一篇《WordPress文章随机显示缩略图的实现方法》

[xx_insert_post station_article=”1223″]

今天我们再来看看如何自动获取文章内第一张图片做为缩略图。

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

//自动获取文章内第一张图片做为缩略图
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;
}



使用方法

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

<?php echo catch_first_image() ?>



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

Leave a Comment