首先贴出所需的css代码,放到你的主题文件style.css里面,要显示的图片的大小可以通过下面的width和height设置:
- .thumbnail_box {
- float: left;
- width: 140px;
- height:100px;
- margin: 17px 10px 8px 15px;_margin: 17px 10px 8px 7px;
- padding: 4px;
- border:1px solid #ccc;}
- .thumbnail img{
- position:absolute;
- z-index:3;}
- 显示缩略图有两种方式:
第一种:随机显示一张图片,这个需要在images文件夹下新建一个文件夹random,里面的图片最好事先处理好大小,名称统一为:tb+数字,如tb1.jpg,tb2.jpg…不要问偶为什么,程序就这么写的,实在懒得改,怕改错!
代码如下,添加到主题文件index.php里面:- <div class="thumbnail_box">
- <div class="thumbnail">
- <?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?>
- <?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
- <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /></a>
- <?php else: ?>
- <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/random/tb<?php echo rand(1,20)?>.jpg" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /></a>
- <?php endif; ?>
- </div></div>
第二种:先从文章中读取图片作为缩略图,如果文章中没有缩略图,再使用上一种方法里面建立的random文件夹里面的图片!
分两步:首先往主题文件functions.php添加如下代码:- if ( function_exists('add_theme_support') )
- add_theme_support('post-thumbnails');
- function catch_first_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(emptyempty($first_img)){
- $random = mt_rand(1, 20);
- echo get_bloginfo ( 'stylesheet_directory' );
- echo '/images/random/tb'.$random.'.jpg';
- }
- return $first_img;
- }
然后在往主题文件index.php里面添加如下代码:
- <div class="thumbnail_box">
- <div class="thumbnail">
- <?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?>
- <?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
- <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /></a>
- <?php else: ?>
- <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
- <?php if (has_post_thumbnail()) { the_post_thumbnail('thumbnail'); }
- else { ?>
- <img class="home-thumb" src="<?php echo catch_first_image() ?>" width="140px" height="100px" alt="<?php the_title(); ?>"/>
- <?php } ?>
- </a>
- <?php endif; ?>
- </div></div>
这就ok了!(原文地址:http://www.yunda51.com/?p=254)
不错不错!