WordPress中实现自动显示文章缩略图
2009-06-26, 发表于: 软件开发 · 标签:php, wordpress · 评论:4
升级到了WordPress 2.8,也产生了修改调整一下界面的想法。这次调整中,除了进一步简化页面,还想实现一个功能,就是在内容摘要中显示文章插图的缩略图。这样看上去图文并茂,会更好看一些。原理很简单,首先利用WordPress提供的get_children()函数,获得文章中的插图附件;然后用 wp_get_attachment_image_src() 函数获得插图的 url。下面是详细的实现过程:

第一步,编写the_image函数
首先编写一个the_image函数,添加到模板的function.php文件中。
function the_image($size = 'medium' , $class = ''){ global $post; //setup the attachment array $att_array = array( 'numberposts' => 1, '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,$class,$url,$caption); //echo the result echo $html; } } } }
在这段代码中有两个关键的函数:
get_children
WordPress Codex的说明:http://codex.wordpress.org/Function_Reference/get_children
使用get_children函数可以获得文章的附件、历史版本、子页面。根据上面的介绍,用法和get_posts类似,参数也是一样的。在the_image中,主要用了下面几个参数:
- numberposts:返回的对象数量,在get_children中,返回的是附件或者历史版本、子页面的数量。
- post_parent:指定文章的id。
- post_type:获得的对象类型。默认是”post”,其他几种是:page、attachment、any。
- post_mime_type:内容类型,这里指定类型是“image”
- order_by:排序的条件。主要有:’author’ ,’category’,'content’ ,’date’ ,’ID’ ,’menu_order’ ,’mime_type’ ,’modified’ ,’,’status’ ,’title’ ,’type’。
wp_get_attachment_image_src
WordPress Codex的说明:http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src
这个函数可以获得指定附件的图像截图(好像不仅仅是获取图像的,其他数据类型的附件也可以获得截图)。
函数的定义:
(array) $image = function wp_get_attachment_image_src($attachment_id, $size=’thumbnail’, $icon = false);
参数:
- $attachment_id:附件的id。
- $size:返回图像的尺寸类型。如果指定的是文本,则是thumbnail, medium, large或者full几种(编辑文章时,在上传图像后,可以看到对应的几种尺寸)。可以用一个数组指定宽和高。
- $icon:是否使用媒体类型图标来取代图像,默认是false。
返回:
这个函数返回一个数组。这个数组有三个元素,分别是:
- $image[0] => url
- $image[1] => width
- $image[2] => height
第二步,修改index.php和archive.php
要在内容列表中显示插图,至少要修改两个文件:index.php和archive.php。在这两个文件中,显示内容摘要的语句是the_content()。在这个语句前加上the_image的调用。例如:
the_image('thumbnail','alignleft'); the_content();
the_image有两个参数:
- $size: size直接传递给wp_get_attachment_image_src,指定获得的图像尺寸。
- $class: 指定img标签的样式类。例如在这个例子中,样式的类是alignleft。这是WordPress模板的一种标准的样式,用于定义左对齐的图像。
存在的问题:
如果文章中的插图是外链的图片,那么可能不受WordPress管理,可能不能正确获得缩略图。
另外发现需要保存一次文章,再插图,这样才能正确获得缩略图。

很早就在看博主的文章了
自己搭了Wordpress后才来留个言
很喜欢博主的文章,支持一个,另外博主的经历貌似跟我有点像,呵呵
正需要谢了!
请问博主,WordPress在调用缩略图的时候是如何获取图片地址的,是从数据库里读取的还是在其他文件中获取的,搬家以后缩略图不显示……纠结中
缩略图地址是由WordPress的相关函数提供的。在我的这个例子中,用的是wp_get_attachment_image_src 获得图片对象,其中包含了图片的url。