今天在写wordpress模版的时候碰到一个很头疼的事,那就是如何获取wordpress文章中的第一张图片并显示在首页,列表页等。而且当文章没有图片是要怎么才能显示默认的图片。后来倒腾了好久终于找到代码,只要将如下代码放入主题的functions.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(emptyempty($first_img)){ //Defines a default image
-
echo get_bloginfo ( 'stylesheet_directory' );
-
echo '/images/default.jpg';
-
//请自行设置一张default.jpg图片
-
}
-
return $first_img;
-
}
将上方代码放入functions.php文件之后在需要显示图片的地方输出图片:
-
<?php echo catch_that_image() ?>
如果你这样设置了,保证你能顺利打输出图片。下面附上我在网上找到的源码,该源码是有错误的,至于错误在哪需要你们慢慢找出来了。
-
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";
-
//请自行设置一张default.jpg图片
-
}
-
return $first_img;
-
}
评论