大多数的wordpress主题模板在首页文章列表和分类栏目页的列表中都会调用文章缩略图,这样现实起来,美观大方.
但是有时候文章没有合适的配图,又或者懒得去弄一张缩略图的时候,现实的默认缩略图又有点单调,而且影响美观.
这时候如果能随机数出一张准备好的图片的话,那是再好不过了.
wordpress模板中实现没有缩略图的时候随机显示指定图片作为缩略图的方法如下:
一般主题中调用缩略图的代码如下:
<?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(); ?>"/></a> <?php else: ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/img.jpg" alt="<?php the_title(); ?>" /></a> <?php endif; ?>
将其修改为:
<?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(); ?>"/></a> <?php else: ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/random/img<?php echo rand(1,5)?>.jpg" alt="<?php the_title(); ?>" /></a> <?php endif; ?>
即可.
代码中的/images/random/img<?php echo rand(1,5)?>.jpg 的意思是随机调用/images/random/img1.jpg到/images/random/img5.jpg中的一个图片,所以需要手动传几张图片到这个目录并且命名为img1.jpg img2.jpg 这样的样子.