您的位置:首页 > 其它

wordpress怎样获得文章中的第一张图片

2013-05-27 10:43 162 查看


wordpress怎样获得文章中的第一张图片

wordpress教程

很多童鞋喜欢在自己的文章中用自定义字段加入一些图片,这样可以美化我们的博客,也会给阅读者带来些轻松的心情。

那我们怎么才可以获得文章中的第一张图片,并把它显示在网页中呢?

首先,打开你主题的Function.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;
}

第二步,在你的模板的主循环中加入以下代码:

<?php echo catch_that_image() ?>

这样就可以把文章中的第一张图片显示在页面上了...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: