首页 > WordPress > WordPress提取文章第一张图片为缩略图 或使用默认图片(纯代码)

WordPress提取文章第一张图片为缩略图 或使用默认图片(纯代码)

时间:2022年6月15日 分类:WordPress 浏览量:562

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

在主题的function文件里,增加以下代码:

//截取内容中第一张图片函数,可作为缩略图
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)){
$first_img = "这里替换一个默认图片路径";
}
return $first_img;
}

需要为此代码准备一张默认缩略图,此外,调用方法是:

<img src="<?php echo catch_first_image() ?>">

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签: