wordpress默认特色图像配合系统的设置是有裁剪功能,但是每次都传还是有点费事,我们一般直接从网络上复制的文章,他默认是不会帮我们裁剪的,假如我们这时候再以第一张图作为缩略图,因为没经过处理,所以会大大增加我们的页面大小,导致打开速度变慢,那么今天就给大家推荐Timthumb工具类专门用于缩略图的生成工作,类文件在文章末尾可以下载。
1、我们把下面的代码粘贴到主题目录:functions.php中
//缩略图开始 function post_thumbnail( $width = 220,$height = 150 ){ global $post; if( has_post_thumbnail() ){ //如果有缩略图,则显示缩略图 $timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full'); $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$timthumb_src[0].'&h='.$height.'&w='.$width.'&zc=1" alt="'.$post->post_title.'" class="thumb" style="display: inline;" />'; echo $post_timthumb; } else { $post_timthumb = ''; ob_start(); ob_end_clean(); $output = preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $index_matches); //获取日志中第一张图片 $first_img_src = get_bloginfo('wpurl').$index_matches [1]; //获取该图片 src if( !empty($first_img_src) ){ //如果日志中有图片 $path_parts = pathinfo($first_img_src); //获取图片 src 信息 $first_img_name = $path_parts["basename"]; //获取图片名 $first_img_pic = get_bloginfo('wpurl'). '/cache/'.$first_img_name; //文件所在地址 $first_img_file = ABSPATH. 'cache/'.$first_img_name; //保存地址 $expired = 604800; //过期时间 if ( !is_file($first_img_file) || (time() - filemtime($first_img_file)) > $expired ){ copy($first_img_src, $first_img_file); //远程获取图片保存于本地 $post_timthumb = '<img src="'.$first_img_src.'" alt="'.$post->post_title.'" class="focus" style="display: inline;" />'; //保存时用原图显示 } $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$first_img_pic.'&h='.$height.'&w='.$width.'&zc=1" alt="'.$post->post_title.'" class="focus" style="display: inline;" />'; } else { //如果日志中没有图片,则显示默认 $post_timthumb = '<img src="'.get_bloginfo("template_url").'/images/default_thumb.gif" alt="'.$post->post_title.'" class="focus" style="display: inline;" />'; } echo $post_timthumb; } } //缩略图结束
2、在网站根目录新建cache文件夹,给予777权限
3、在模板里面调用:
post_thumbnail(243,182);
通过上面的操作,我们再刷新页面发现打开速度是不是大大的提升了!
timthumb.php文件下载,请至文章末尾处
评论前必须登录!
注册