給文章一個個的設置縮略圖嫌麻煩?試試這個隨機縮略圖代碼,可以顯示隨機縮略圖。
將以下代碼添加至主題根目錄下的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(); ?>
經測試發現,該代碼僅返回隨機縮略圖地址。