您的位置:首页»WordPress 教程, 主题开发, 进阶使用»  自动获取 WordPress 缩略图

自动获取 WordPress 缩略图

sofish 小盆友在他的博客中提到一直没有找到自动显示 WordPress 缩略图的方法,很多主题也只是通过利用 WordPress 中的自定义字段(custom field)功能来曲线救国。但是,这种方法相当不自动,每次都得复制一遍缩略图地址,不是我们鱼类思维。大家知道,每当我们利用 WordPress 后台上传图片时,WordPress 都会自动为我们创建一个缩略图,那么,我们是否可以自动获取这个缩略图呢?答案是肯定的。下面我们一起来看看这篇 WordPress 教程
首先,我们将以下代码复制到你主题的 functions.php 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function the_image($size = 'medium' , $class = ''){
	global $post;
 
	//setup the attachment array
	$att_array = array(
		'post_parent' => $post->ID,
		'post_type' => 'attachment',
		'post_mime_type' => 'image',
		'order_by' => 'menu_order'
	);
 
	//get the post attachments
	$attachments = get_children($att_array);
 
	//make sure there are attachments
	if (is_array($attachments)){
		//loop through them
		foreach($attachments as $att){
			//find the one we want based on its characteristics
			if ( $att->menu_order == 0){
				$image_src_array = wp_get_attachment_image_src($att->ID, $size);
 
				//get url - 1 and 2 are the x and y dimensions
				$url = $image_src_array[0];
				$caption = $att->post_excerpt;
				$image_html = '<img class="%s" src="%s" alt="%s" />';
 
				//combine the data
				$html = sprintf($image_html,$url,$caption,$class);
 
				//echo the result
				echo $html;
			}
		}
	}
 
}

以上代码会自动列出 WordPress 文章中的所有附件图片,并显示第一张图片的缩略图。
接下来,我们只需在 index.php 等文件中添加以下代码,获取 WordPress 缩略图

<?php the_image('thumbnail','post-thumb'); ?>

当然,我们也可以显示中等尺寸的缩略图

<?php the_image('medium','post-image'); ?>

当然,以上代码还有一点点效率问题,如果你有更好的 idea 只匹配第一张图片并显示其缩略图,请 share with us!!!
本文译自:Post image the easy peasy way
中文翻译:自动获取 WordPress 缩略图

10个评论

  • Reply 1 sofish

    January 14th, 2009 at 22:23

    靠,“鱼类思想”,你哪来那么多词。不过,这个不是文章缩烈图。而是可以做gallery…

    • Reply 2 辐射鱼

      January 14th, 2009 at 22:38

      囧,应该是不止能实现缩略图吧?你这错字整得……应该还可以实现图片分类、thickbox 效果

  • Reply 3 Oscar

    January 15th, 2009 at 15:55

    能给个演示看看吗?

    • Reply 4 辐射鱼

      January 15th, 2009 at 16:16

      请看“自动获取 WordPress 缩略图增强应用”的视频

  • Reply 5 wdpress

    January 22nd, 2009 at 13:48

    鱼,你的代码显示插件是什么?
    我用了几个都不行,很痛苦

    • Reply 6 辐射鱼

      February 2nd, 2009 at 09:51

      WP-Syntax,用的是pre标签,要用code就更完美了

  • Reply 7 布谷鸟

    May 10th, 2009 at 22:44

    既然是找第一张图片,就不要用preg_match_all,
    用preg_match就行了,找到就完事了。
    请看插件:http://niaolei.org.cn/posts/4012

    • Reply 8 辐射鱼

      May 12th, 2009 at 06:53

      woo,你那个插件非常有用。它这个使用的是globle查询,没有像你一样使用preg_match,还是比较费资源

  • Reply 9 5sign

    September 23rd, 2009 at 16:01

    不错.我的网站就是用这个方法.还行. 谢谢..