wordpress获取文章中第一张图片

wordpress获取文章中第一张图片

对于这个需求我想大多数主题开发者都有,毕竟每篇文章如果都要自己上传缩略图来当封面啥的就太麻烦了,所以这个时候我们就需要有一个方法来获取文章中的所有图片中的一张来使用,随便拿来干嘛。

当然,这些都是废话,其实我想要说的是百度上面有很多这样的代码,但都是错的……

下面贴出两组代码。

unction catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.>/i', $post->post_content, $matches);

//获取文章中第一张图片的路径并输出
$first_img = $matches [1] [0];

//如果文章无图片,获取自定义图片

if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";

//请自行设置一张default.jpg图片
}

return $first_img;
}
/<img.>

其实你如果直接拿来用,你会发现是可以用的,看起来还像没什么问题,但是如果你一篇文章中有很多图片,你就会发现这个函数取的其实是最后一张,不是第一张!

正确的代码

// 获取文章第一张缩略图
function catch_that_image() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//iU', wp_unslash($post->post_content), $matches);
if(empty($output)){
$first_img = "https://paperdrips.s3.amazonaws.com/prod/fs/cachedimages/3727365566-08cce0080760678feb08fd1abb3196a2a15c12274eac42fc436be4cc39cceae4.png";
}else {
$first_img = $matches [1][0];
}
return $first_img;
}

错误地方

其实错的地方主要是正则,我在我的代码的正则后面加了一个大写的U,至于为什么要加这个,你就可以去百度一下了。


分享到:


相關文章: