我写的 七牛云存储 WordPress 插件只是使用七牛的镜像功能,而 WordPress 后台的图片浏览其实并没有使用七牛的镜像源。很多人,如果 WordPress 后台也要使用七牛图片,怎么处理,于是我写了下面这段代码:
* 注意,我使用的 PHP 闭包函数来处理,所以要新点的版本的 PHP 才行,具体哪个版本支持 PHP 闭包函数,自行查阅一下。
// 因为使用七牛来缩图,WordPress 默认的缩图就没有必要了。 add_filter('pre_option_thumbnAIl_size_w', '__return_zero' ); add_filter('pre_option_thumbnail_size_h', '__return_zero' ); add_filter('pre_option_medium_size_w', '__return_zero' ); add_filter('pre_option_medium_size_h', '__return_zero' ); add_filter('pre_option_large_size_w', '__return_zero' ); add_filter('pre_option_large_size_h', '__return_zero' ); // 因为使用七牛来缩图,也不用生成各种尺寸的数组 add_filter('intermediate_image_sizes_advanced', function($sizes){ if(isset($sizes['full'])){ return array('full'=>$sizes['full']); }else{ return array(); } }); // 因为使用七牛来缩图,后台图片选择只剩下原图 add_filter('image_size_names_choose', function($sizes){ if(isset($sizes['full'])){ return array('full'=>$sizes['full']); }else{ return array(); } }); add_filter('upload_dir', function($uploads){ $uploads['url'] = wpjam_get_thumbnail($uploads['url']); $uploads['baseurl'] = wpjam_get_thumbnail($uploads['baseurl']); return $uploads; }); add_filter('wp_calculate_image_srcset_meta', '__return_empty_array'); // 因为使用七牛来缩图,根据各种尺寸,使用七牛的缩图API进行缩图 add_filter('wp_get_attachment_image_src', function($image, $attachment_id, $size, $icon){ return wpjam_get_attachment_image_src($attachment_id, $size); }, 10 ,4); function wpjam_get_attachment_image_src($attachment_id, $size='full'){ $img_url = wp_get_attachment_url($attachment_id); if(emptyempty($img_url)){ return array('', 0, 0, false); } $image_meta = wp_get_attachment_metadata( $attachment_id ); $crop = 0; if($size == 'thumbnail'){ $crop = 1; $width = $height = 150; }elseif($size == 'medium'){ $width = $height = 300; }elseif($size == 'medium_large'){ $width = 768; $height = 0; }elseif($size == 'large'){ $width = $height = 1024; }elseif(is_array($size)){ $width = $size[0]; $height = $size[1]; } if(isset($width) && isset($height)){ $mode = $crop?'1':'2'; $img_url = wpjam_get_thumbnail($img_url, compact('width', 'height', 'mode')); $dims = image_resize_dimensions($image_meta['width'], $image_meta['height'], $width, $height, $crop); return array( $img_url, $dims[4], $dims[5],false); }else{ $img_url = wpjam_get_thumbnail($img_url); $image_meta_width = ($image_meta['width'])??0; $image_meta_height = ($image_meta['height'])??0; return array($img_url, $image_meta_width, $image_meta_height, false); } } // 媒体列表页面,也是使用七牛的缩图API进行缩图 add_filter('wp_prepare_attachment_for_js', function($response, $attachment, $meta){ if(isset($response['sizes'])){ $orientation = $response['sizes']['full']['orientation']; foreach (array('thumbnail', 'medium', 'medium_large', 'large') as $s) { $image_src = wpjam_get_attachment_image_src($attachment->ID, $s); $response['sizes'][$s] = array( 'url' => $image_src[0], 'width' => $image_src[1], 'height' => $image_src[2], 'orientation' => $orientation ); } } return $response; }, 10, 3);