首先给大家展示一下,目前设置缩略图的四种方法(详见下图),我按照自己的理解将其排列成如下顺序,并且在图中列出了各种实现缩略图的方法的图片来源,通过自定义字段可以调用外链图片,而后面三种方法仅能使用本地图片。
下面我通过分层条件判断语句的方式,将上述四种缩略图调用方式整合到一起,并设置成四个顺序执行的环节,只有当上面的条件不满足的时候,才会顺次对下面的条件进行判断,并执行相应的语句。(详见下图)
下面就到了见证奇迹的时刻,请看缩略图实现代码。
<div class="thumb"> <?php if ( get_post_meta($post->ID, '缩略图', true) ){ ?> <?php $image = get_post_meta($post->ID, '缩略图', true); ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" > <img width="160px" height="160px" src="<?php echo $image; ?>" alt="<?php the_title(); ?>"/></a> <?php } elseif(has_post_thumbnail()){?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" > <img src="<?php bloginfo('stylesheet_directory'); ?>/timthumb.php?src=<?php get_image_url(); ?>&h=160&w=160&zc=1" alt=""/></a> <?php } elseif(catch_that_image()){?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" > <img src="<?php echo catch_that_image()?>" width="160px" height="160px" alt="<?php the_title(); ?>"/></a> <br /> <?php } else { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" > <img src="<?php bloginfo('stylesheet_directory'); ?>/timthumb.php?src=<?php bloginfo('template_directory'); ?>/images/thumbnail.jpg&h=160&w=160&zc=1" alt="" /> </a> <?php } ?> </div>
为了使上述代码能够流畅的运行,还有几件事情需要做;
第一件事情是确保当前所用wordpress主题支持特色图像功能,查看一下主题的function文件中是否有
add_theme_support('post-thumbnails')
这一语句,没有的话请添加上;
第二件事情是为了实现抓取正文中第一张图片做缩略图的功能,需要在当前主题的function文件中添加如下函数:
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] ;
if(empty($first_img)){ //Defines a default image
$first_img ="0";
}
return $first_img;
};