您的位置:首页 > 编程语言

WordPress主题自动显示文章第一张图片代码

2012-09-23 00:00 363 查看
在修改主题的时候,我们可能需要WordPress自动获取文章第一张图片,在博客吧看到了相关的实现方法,记录一下,估计以后也用得到。
在当前使用的主题模板的functions.php文件<?php和?>之前添加以下代码
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)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}在当前主题模板的index.php文件的内容代码前或后添加以下代码
<?php echo catch_that_image() ?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: