前面写过一篇《PHP获取bbpress帖子内第一张图片并调用出来的代码》,现在来分享一段如何在wordpress里获取文章首图的代码:
function catch_that_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 = "/images/default.jpg"; //默认图片地址需自己设置
}
return $first_img;
}
这里定义了一个函数 catch_that_image,将这段代码放在主题文件夹下的functions.php里即可。
然后在需要调用的地方,用
<?php echo catch_that_image() ?>
就可以将每一篇文章中的第一张图片调用出来了。