残念ながら、@ Patrickの答えは、WP 4.4で導入されたsrcset関数を破壊します。幸いなことに、2つの追加関数を追加するだけです!
まず、登録されているすべてのサムネイルサイズをイメージメタデータに一時的に再導入して、それらが考慮されるようにする必要があります。
function bi_wp_calculate_image_srcset_meta($image_meta, $size_array, $image_src, $attachment_id){
//all registered sizes
global $_wp_additional_image_sizes;
//some source file specs we'll use a lot
$src_path = get_attached_file($attachment_id);
$src_info = pathinfo($src_path);
$src_root = trailingslashit($src_info['dirname']);
$src_ext = $src_info['extension'];
$src_mime = wp_check_filetype($src_path);
$src_mime = $src_mime['type'];
$src_base = wp_basename($src_path, ".$src_ext");
//find what's missing
foreach($_wp_additional_image_sizes AS $k=>$v)
{
if(!isset($image_meta['sizes'][$k]))
{
//first, let's find out how things would play out dimensionally
$new_size = image_resize_dimensions($image_meta['width'], $image_meta['height'], $v['width'], $v['height'], $v['crop']);
if(!$new_size)
continue;
$new_w = (int) $new_size[4];
$new_h = (int) $new_size[5];
//bad values
if(!$new_h || !$new_w)
continue;
//generate a filename the same way WP_Image_Editor would
$new_f = wp_basename("{$src_root}{$src_base}-{$new_w}x{$new_h}." . strtolower($src_ext));
//finally, add it!
$image_meta['sizes'][$k] = array(
'file' => $new_f,
'width' => $new_w,
'height' => $new_h,
'mime-type' => $src_mime
);
}
}
return $image_meta;
}
add_filter('wp_calculate_image_srcset_meta', 'bi_wp_calculate_image_srcset_meta', 10, 4);
次に、一致を実行して、不足しているサムネイルを生成する必要があります。
function bi_wp_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id){
//get some source info
$src_path = get_attached_file($attachment_id);
$src_root = trailingslashit(pathinfo($src_path, PATHINFO_DIRNAME));
//the actual image metadata (which might be altered here)
$src_meta = wp_get_attachment_metadata($attachment_id);
//an array of possible sizes to search through
$sizes = $image_meta['sizes'];
unset($sizes['thumbnail']);
unset($sizes['medium']);
unset($sizes['large']);
$new = false;
//loop through sources
foreach($sources AS $k=>$v)
{
$name = wp_basename($v['url']);
if(!file_exists("{$src_root}{$name}"))
{
//find the corresponding size
foreach($sizes AS $k2=>$v2)
{
//we have a match!
if($v2['file'] === $name)
{
//make it
if(!$resized = image_make_intermediate_size(
$src_path,
$v2['width'],
$v2['height'],
$v2['crop']
)){
//remove from sources on failure
unset($sources[$k]);
}
else
{
//add the new thumb to the true meta
$new = true;
$src_meta['sizes'][$k2] = $resized;
}
//remove from the sizes array so we have
//less to search next time
unset($sizes[$k2]);
break;
}//match
}//each size
}//each 404
}//each source
//if we generated something, update the attachment meta
if($new)
wp_update_attachment_metadata($attachment_id, $src_meta);
return $sources;
}
add_filter('wp_calculate_image_srcset', 'bi_wp_calculate_image_srcset', 10, 5);