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() ?>
这样就可以把文章中的第一张图片显示在页面上了...