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

现在很多WordPress主题模板都有提供缩略图的位置,比如笔者这个博客现在采用的主题就有缩略图。很多时候我们但是自己设置缩略图的,比如找一张与文章内容锲合度较高的图片作为缩略图单独上传,如果有朋友嫌弃这样操作太麻烦,而想能不能这样:wordpress获取文章内第一张图为缩略图呢?那么今天我们再来看看如何自动获取文章内第一张图片做为缩略图。

自动的采用WordPress获取文章内第一张图为缩略图,这将大大减少我们的工作量,这不失为一个好的方法。我们可以采用下面的方法实现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;
}

使用方法

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

<?php echo catch_first_image() ?>

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

通过以上的方法我们就能实现WordPress获取文章内第一张图为缩略图了。

<<<<<<便宜稳定美国VPS推荐>>>>>>搬瓦工VPS年付49.99美元起

未经允许不得转载:便宜VPS网 » WordPress如何获取文章内第一张图为缩略图