众所周知,网站最怕改版,其中一个主要的原因就是缩略图的问题,旧模板的缩略图尺寸不一定适合新版的模板缩略图尺寸要求,尽管后台的设置-多媒体-缩略图尺寸修改了,可这是新上传的图片才会生成新的尺寸的缩略图,建站网想了很多办法,也从郑力大神那看到用ps加数据库批量的方法,可是建站网里图片太多,缩略图尺寸也复杂不一,曾经还做过中文文件名md5转换,用ps家数据库批量的方法实在是复杂和累人!如何才能快速又方便的解决wordpress缩略图尺寸重新裁剪的问题呢?从奶嘴那了解到谷歌的timthumb很好用,建站网就百度了下,确实找到相关的文献,通过摸索,现在通过timthumb就可以自由的给缩略图裁剪自己设定的缩略图,可以说一个文章的缩略图可以有几个缩略图的尺寸,做到全站所有要展现缩略图的地方的尺寸都是最清晰的!下面我们来看教程:
02 |
function post_thumbnail( $width = 100,$height = 80 ){ |
04 |
if( has_post_thumbnail() ){ |
05 |
$timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full'); |
06 |
$post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$timthumb_src[0].'&h='.$height.'&w='.$width.'&zc=1" echo $post_timthumb; |
11 |
$output = preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',$post->post_content, $index_matches); |
12 |
$first_img_src = $index_matches [1]; |
13 |
if( !empty($first_img_src) ){ |
14 |
$path_parts = pathinfo($first_img_src); |
15 |
$first_img_name = $path_parts["basename"]; |
16 |
$first_img_pic = get_bloginfo('wpurl').'/cache/'.$first_img_name; |
17 |
$first_img_file = ABSPATH. 'cache/'.$first_img_name; |
19 |
if ( !is_file($first_img_file) || (time() -filemtime($first_img_file)) > $expired ){ |
20 |
copy($first_img_src, $first_img_file); |
21 |
$post_timthumb = '<img src="'.$first_img_src.'" |
23 |
$post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$first_img_pic.'&h='.$height.'&w='.$width.'&zc=1" } else { |
24 |
$post_timthumb = '<img src="'.get_bloginfo("template_url").'/images/default_thumb.gif" } |
将上面的代码放进WP的主题模板文件夹functions.php内,然后下载timthumb.php 文件放到主题根目录下!然后通过:
1 |
<?php post_thumbnail(243,182); ?> |
这个函数就可以调用出裁剪好尺寸为243*182的缩略图了,相应的缩略图结构代码参照:
1 |
<a href="<?php echo get_permalink(); ?>" title="<?php the_title(); ?>"><?php post_thumbnail(243,182); ?></a> |
其中243代表宽,182代表高,你们在使用的时候替换成你们的尺寸即可!然后我们还要给网站根目录下创建cache目录,并给予777权限,这样就可以全自动调用裁剪好的缩略图了,而这些缩略图也就都存在了cache文件夹里,使用起来很方便!
这个时候有人会问,那系统自带的生成缩略图的功能这么办?每次上传图片,系统都会生成几个尺寸的缩略图,有了timthumb还需要系统自带的缩略图生成功能吗?建站网的回答是:随便你!WP批量删除全部文章缩略图的方法是在functions.php内加入以下代码:
03 |
$attachments = $wpdb->get_results( " |
06 |
WHERE meta_key = '_thumbnail_id' |
08 |
foreach ( $attachments as $attachment ) { |
09 |
wp_delete_attachment( $attachment->meta_value, true ); |
12 |
DELETE FROM $wpdb->postmeta |
13 |
WHERE meta_key = '_thumbnail_id' |
执行前要考虑好哈,别怪小2没提醒,一删除就全部没有了,并且以后也不想生成缩略图的话,这个代码就放文件里好了,如果以后还想生成新的缩略图的话,使用一次后就要把这代码删除了。。。别到时候就悲剧了!