自动提取文章的第一张图片

1、在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 = "在这里指定如果没有图片则显示的默认图片路径";
}
return $first_img;
}

2、在需要显示图片的地方添加如下:

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

有必要的话需要在css里定义图片的尺寸之类。比较有用的技巧,来自:jinwen

14 Comments
  1. 2009.10.21 at 09:17 Notify

    你又开始折腾Wordpress啦?

  2. 2009.10.21 at 10:00 Notify

    @ZH CEXO:是啊,最近做一个站,找到什么好东西就随手贴上了了。呵呵

  3. 2009.10.21 at 10:43 Notify

    比较有用。尺寸在css里面定义的话,图片就都一样大小了吧。

  4. 2009.10.21 at 10:48 Notify

    @Eden:是的,我试过了,可以设置成一样大小,不过如果图片长宽比例不一样,有些图片会变形

  5. 2009.10.21 at 11:20 Notify

    我以前的主题就是用这个方法来获取缩略图的。。但现在没有加入。。

  6. 2009.10.26 at 17:47 Notify

    Jinwen那看过方法

  7. 2009.10.31 at 21:15 Notify

    今天你偷菜了没有?戴斯克姆

  8. 2009.11.02 at 00:21 Notify

    不错哦,我也开了一个博客,有空大家经常交流…

  9. 2009.11.02 at 19:51 Notify

    博主的文采不错,大家有空多交流!

  10. 2009.11.06 at 17:17 Notify

    好呀 很有用!!

  11. 2009.12.03 at 08:19 Notify

    小墨好呀 ~( ̄▽ ̄)~*

  12. 2009.12.19 at 21:40 Notify

    小墨好。

  13. 2009.12.22 at 21:58 Notify

    这个还是不错的 呵呵 折腾模板的人管用

  14. 2010.01.02 at 02:37 Notify

    我喜欢折腾,不过现在的主题好像不适合用这个:-)

在下边留言吧!