巧用 WordPress 缩略图
时间:2009年12月12日作者:青雨被围观 428 次评论次数:0
WordPress 不仅是博客, 很多时候 WordPress 还被用作为 CMS (内容管理系统). 博主们喜欢为每个文章加上统一大小的缩略图, 尤其是信息类平台. 其中比较常用的处理办法是用 custom field 向文章插入图片, 通过上传大小一致的小图或者使用 phpThumb 等工具生成缩略图.
2.7 开始, WordPress 大幅提升多媒体功能, 越来越多人使用 WP 的内置图片仓库. 对这些用户来说, 制作缩略图变得并不那么困难, 在上传图片的时候就会默认生成 150×150 规格的小图 (如果图片高度/宽度不足 150px, 使用原高度/宽度). 那我们可以充分利用这个功能, 在文章列表上加上这个图片作为缩略图. 这样处理各有利弊, 好处是简单, 智能 (不用每次输入缩略图), 坏处是消耗服务器流量.
Okay, 现在要做的就是提取上传生成的小图片, 并放置在文章的适当位置. 我创建了一个文件 thumb.php, 图片获取和调用一起处理, 文件内容如下.
<?php
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image'
);
$images = &get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
$imageUrl = '';
if ($images) {
$image = array_pop($images);
$imageSrc = wp_get_attachment_image_src($image->ID);
$imageUrl = $imageSrc[0];
}else{
$imageUrl = get_bloginfo('template_url') . '/img/default.gif';
}
?>
<a href="<?php the_permalink() ?>"><img class="left" src="<?php echo $imageUrl; ?>" alt="<?php the_title(); ?>" width="150" height="150" /></a>这段代码会去找第一个上传的图片缩略图 (如果第一个图片被删除, 则找第二个的, 如此类推…), 如果找不到任何上传图片则使用默认图片. 代码中用到 get_children 和 wp_get_attachment_image_src 两个方法,
然后在文章列表 index.php, 存档页面 archive.php 和搜索页面 search.php 中调用, 调用代码如下.
<img src="{某透明图片的 URL}" alt="Google" style="background:url(http://www.google.com/intl/en_ALL/images/logo.gif) no-repeat 50% 50%;width:150px;height:150px;" />这段代码是把图片放在文章内容前面, 图片如何摆放需要用 CSS 调整一下布局, 这里就不多说了.
最后两个问题.
1. 如果图片高度或者宽度不足 150px, 这样做必然将图片拉伸, 很不美观. 用什么办法可以让图片都显示为 150×150, 并居中显示? 提示: 可以用 CSS 实现, 类似方法可以在Elegant Box 主题中找到.
<img src="./UpZnztblog/s.gif" alt="<?php the_title(); ?>" style="background:url(<?php echo $imageUrl; ?>) no-repeat 50% 50%;width:150px;height:150px;" />
2. 在文章列表中, 我们只希望看到缩略图, 而屏蔽其他所有图片, 除了使用文章摘要去除所有标签样式, 是否有其他方法可以做到?
<?php
include('thumb.php');
$content = apply_filters('the_content', $content);
$content = preg_replace(“/<img[^>]+\>/i”, “”, $content);
?>
暂时没有评论!