首页 » 网站建设 » wordpress技巧 » 网站建设 » 阅读文章

WordPress自动读取文章第一张图片代码

2011-02-14 21:34 1817 0
标签:

写代码来自动读取文章里插入的第一张图片,然后在首页适当位置调用,是十分方便的,而且不需要使用特色图片设定和自定义域生成,免去复制图片地址的烦恼,具体代码该怎么写,如下:

在functions.php文件里插入以下自定义函数

01 //get image
02 function catch_that_image() {
03 global $post, $posts;
04 $first_img = '';
05 ob_start();
06 ob_end_clean();
07 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
08 $first_img = $matches [1] [0];
09 if(empty($first_img)){
10 $first_img = bloginfo('template_url'). '/images/default-thumb.jpg';
11 }
12 return $first_img;
13 }

当文章中没有图片的时候,将会使用默认图片替换,可自定义,把图片放到下面路径即可,images/default-thumb.jpg,文件名要跟代码匹配。

在适当的首页位置插入以下代码调用图片,其他页面位置类同。

1 <img src="<?php echo catch_that_image() ?>" />

联系我 Contact Me

回到页首