大多数写博客的人不习惯添加特色图片,我们通过修改代码让首页和列表页自动调用文章都能显示缩略图,调用的优先级如下:
文章已有特色图片>文章内第一张图片>随机缩略图
操作步骤
1、复制上面代码粘贴到主题functions.php中;
2、在主题中新建/images/random/目录,找一些自己喜欢的图片上传进去。将他们重命名为1,2,3,4,5…….jpg;
3、在想要展示缩略图的地方添加代码:
<?php echo catch_first_image(); ?>
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(!empty($first_img))
{
$image_size = getimagesize($first_img);
$image_width = $image_size[0];
}
//如果第一张图不存在或过小,则返回随机图片
if(empty($first_img) || $image_width<50){
$first_img = '';
//从10张图中随机选择,可根据自己的图片数量设置
$random = mt_rand(1, 10);
echo get_bloginfo ( 'stylesheet_directory' );
echo '/images/random/'.$random.'.JPG';
}
return $first_img;
}