给文章一个个的设置缩略图嫌麻烦?试试这个随机缩略图代码,可以显示随机缩略图。
将以下代码添加至主题根目录下的functions.php文件中的<?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 = ''; //从2张图中随机选择,可根据自己的图片数量设置 $random = mt_rand(1, 2); echo get_bloginfo ( 'stylesheet_directory' ); echo '/images/random/'.$random.'.jpg'; } return $first_img;}在主题中新建/images/random/目录,找一些自己喜欢的图片上传进去。将他们重命名为 1,2,3,4,5.jpg。
调用代码:
<?php echo catch_first_image(); ?>经测试发现,该代码仅返回随机缩略图地址。
