不想每篇博文都制作(Copy)缩略图。。。于是就。。。
木有抄其它主题的一点代码,采集君就放过我吧。。。
Step1
将下面的代码添加到functions.php中
function get_rand_thum_img(){ $randimgdfile=array(); //缓存过期时间(秒) $randimgcact = 2592000 ; //Path $randimgdpath = get_stylesheet_directory().'/randimg/'; $randimgupath = get_stylesheet_directory_uri().'/randimg/'; //Path-END //使用WP数据库缓存文件列表,减少HDD IO 读取 $randimgdtmp = get_option('shenqhy_randimg'); if (!$randimgdtmp) { $randimgdfile = glob($randimgdpath.'*.png'); update_option('shenqhy_randimg',serialize(array('time'=>time(),'data'=>$randimgdfile))); }else{ $randimgdtmp = unserialize($randimgdtmp); $randimgexpt = (time() - $randimgdtmp['time']); if ($randimgexpt>$randimgcact || $randimgexpt<0) { $randimgdfile = glob($randimgdpath.'*.png'); update_option('shenqhy_randimg',serialize(array('time'=>time(),'data'=>$randimgdfile))); }else{ $randimgdfile = $randimgdtmp['data']; } } //计数文件数量,为随机发生器做准备 $randimgfcoun = count($randimgdfile); //随机发生 $randimgrfile = rand(0,($randimgfcoun-1)); //生成图片链接 $randimguout = $randimgupath.str_replace($randimgdpath, '', $randimgdfile[$randimgrfile]); //销毁变量 unset($randimgdfile,$randimgdpath,$randimgupath,$randimgfcoun,$randimgrfile); //返回图片链接 return $randimguout; }
Step2
下载 randimg.zip(1.7M) 解压,上传至主题目录中
修改主题代码为:
以博主目前使用的主题为例:
function deel_thumbnail() { global $post; if ( has_post_thumbnail() ) { $domsxe = simplexml_load_string(get_the_post_thumbnail()); $thumbnailsrc = $domsxe->attributes()->src; echo '<img src="'.$thumbnailsrc.'" alt="'.trim(strip_tags( $post->post_title )).'" />'; } else { $content = $post->post_content; preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER); $n = count($strResult[1]); if($n > 0){ echo '<img width="220" height="150" src="'.get_bloginfo("template_url").'/timthumb.php?src='.$strResult[1][0].'&w=220&h=150&zc=1" alt="'.trim(strip_tags( $post->post_title )).'" />'; }else { echo '<img width="220" height="150" src="'.get_rand_thum_img().'" alt="'.trim(strip_tags( $post->post_title )).'" />'; } } }至于其它主题,就请各位友友自行修改了。。。
其实呢,大家还可以自己添加图片到存放缩略图的文件夹中,但最好别用除大小写字母和数字以及 -_ 之外的字符。
不过嘛,用也行,最好是得把上面的 $randimguout = $randimgupath.urlencode(str_replace($randimgdpath, '', $randimgdfile[$randimgrfile]));
改成 $randimguout = $randimgupath.urlencode(str_replace($randimgdpath, '', $randimgdfile[$randimgrfile]));
转载请注明:神奇海域 » WordPress 无插件添加随机缩略图