我想向媒体上载程序添加自定义图像大小:
为了做到这一点,我使用以下代码(为了方便起见,这里有注释):
// this function adds the custom image sizes to the media uploader
function my_insert_custom_image_sizes( $sizes ) {
// get the custom image sizes
global $_wp_additional_image_sizes;
// if there are none, just return the built-in sizes
if ( empty( $_wp_additional_image_sizes ) )
return $sizes;
// add all the custom sizes to the built-in sizes
foreach ( $_wp_additional_image_sizes as $id => $data ) {
// take the size ID (e.g., \'my-name\'), replace hyphens with spaces,
// and capitalise the first letter of each word
if ( !isset($sizes[$id]) )
$sizes[$id] = ucfirst( str_replace( \'-\', \' \', $id ) );
}
return $sizes;
}
// define the init function next, which sets up all the necessary stuff
function custom_image_setup () {
add_theme_support( \'post-thumbnails\' );
add_image_size( \'my-size1\', 250, 250 );
add_image_size( \'my-size2\', 350, 350 );
add_image_size( \'my-size3\', 450, 450 );
add_filter( \'image_size_names_choose\', \'my_insert_custom_image_sizes\' );
}
// attach that init function to the \'after_setup_theme\' hook
// so it runs on each page load once your theme\'s been loaded
add_action( \'after_setup_theme\', \'custom_image_setup\' );
此代码工作正常。还有一个问题:上载图像时,如果图像小于最小自定义图像大小的尺寸,则会出现以下错误:
Invalid argument supplied for foreach()
.
我想问题来自my_insert_custom_image_sizes
作用因此,基本上,当没有生成自定义图像时,会出现错误。我怎样才能解决这个问题?我有一种感觉,问题很简单,我忽略了,但我迷路了。。。
如果要复制此错误,只需将上述代码粘贴到函数中,然后上载一个smaller 大于250x250像素。
UPDATE: 经过进一步研究,该错误似乎与我的JPEG压缩函数中的foreach有关:
// Set JPEG compression quality
add_filter(\'jpeg_quality\', create_function(\'$quality\', \'return 100;\'));
add_action(\'added_post_meta\', \'ad_update_jpeg_quality\', 10, 4);
function ad_update_jpeg_quality($meta_id, $attach_id, $meta_key, $attach_meta) {
if ($meta_key == \'_wp_attachment_metadata\') {
$post = get_post($attach_id);
if ($post->post_mime_type == \'image/jpeg\') {
$pathinfo = pathinfo($attach_meta[\'file\']);
$uploads = wp_upload_dir();
$dir = $uploads[\'basedir\'] . \'/\' . $pathinfo[\'dirname\'];
foreach ($attach_meta[\'sizes\'] as $size => $value) {
$image = $dir . \'/\' . $value[\'file\'];
$resource = imagecreatefromjpeg($image);
if ($size == \'large\') {
// set the jpeg quality for \'large\' size
imagejpeg($resource, $image, 35);
} elseif ($size == \'medium\') {
// set the jpeg quality for the \'medium\' size
imagejpeg($resource, $image, 35);
} elseif ($size == \'small\') {
// set the jpeg quality for the \'small\' size
imagejpeg($resource, $image, 40);
} else {
// set the jpeg quality for the rest of sizes
imagejpeg($resource, $image, 90);
}
imagedestroy($resource);
}
}
}
}
有什么想法吗?有什么问题吗?