I put an avatar uploader on the site, I want it to be cut to 3 sizes (original, 32 x 32 and 96 x 96) after the image is uploaded. So I defined 2 sizes as below :
add_image_size( 'avatar_scale_32x32', 32, 32, false );
add_image_size( 'avatar_scale_96x96', 96, 96, false );
My site has other sizes that I have defined for other uploaders, Now I want to specify that if an image is uploaded from this uploader it will crop only the sizes that are related to it. name="wpua-file"
.
This is the code I use, but it cuts the image to all sizes, not the desired sizes.
function remove_default_img_sizes( $sizes ) {
$targets = ['avatar_scale_32x32', 'avatar_scale_96x96'];
foreach( $sizes as $size_index => $size ) {
if ( $_FILES['wpua-file'] ) {
if( in_array( $size, $targets ) ) {
unset( $sizes[$size_index] );
}
}
}
return $sizes;
} add_filter( 'intermediate_image_sizes', 'remove_default_img_sizes', 10, 1 );
Where am I doing wrong?
The code I put in the question, if I upload an image from the target uploader, it creates all the sizes except the sizes inside the $targets
array. If I want it to be the opposite, that is, it disables all sizes other than the sizes in the $targets
array when uploading and creates only 2 sizes in the $targets
array. in_array( $size, $targets )
If the sizes are other than the 2 sizes in the $targets
array, it returns the false value, then 2 correct values are returned according to the 2 sizes in the $targets
array. That's why we say include values that are false :
function remove_default_img_sizes( $sizes ) {
$targets = ['avatar_scale_32x32', 'avatar_scale_96x96'];
foreach( $sizes as $size_index => $size ) {
var_dump( in_array( $size, $targets ) );
if ( $_FILES['wpua-file'] ) {
if ( in_array( $size, $targets ) === false ) {
unset( $sizes[$size_index] );
}
}
}
return $sizes;
} add_filter( 'intermediate_image_sizes', 'remove_default_img_sizes', 10, 1 );