I use various custom image sizes (by add_image_size
) and I have set my JPEG compression to 30% with this filter:
function jpeg_quality_callback($arg) {
return (int)30;
}
add_filter('jpeg_quality', 'jpeg_quality_callback');
If I am not mistaken, the above code compresses all of my custom image sizes with 30%. Now, for two of my custom image sizes named splash1
and splash2
, I want to set the compression to 80%. How is this possible?
Or alternatively, exclude those image sizes from the 30% compression filter.
The
'jpeg_quality'
filter hook functions accept two arguments:$jpeg_quality
and$function
which is the function from within the filter hook is fired and can be eitherimage_resize
orwp_crop_image
. So there is no way to selectively set the quality of.jpeg
images according to image size from this filter hook function.However, you still can hook to a later action hook in the process of uploading attachments and adjust the
.jpeg
image quality of uploaded images at that point according to thier specific size to suit your needs. First set thejpeg_quality
to the maximum to preserve the original image quality, then hook toadded_post_meta
action hook (which is fired at the end of inserting attachment metadata`) to adjust the quality, as follow:The above code will affect the newly uploaded images only. If you want to update the quality of previously uploaded images, you can utilize
register_activation_hook
of plugins. Create a new php file inwp-content/plugins
directory and name it whatever you like (update-jpeg-quality.php
for example) and add the following code to it:Now visit your Plugins page and hit
activate
of theUpdate JPEG Quality
plugin. This will loop through all your previously uploaded.jpeg
images and adjust their quality according to the values and conditions you specify in the plugin. Then you can safely deactivate and delete this plugin. Please test on testing environment first before applying to production site.