Short. I want ”large’ images compressed by 90%, and ‘medium’ to be by 60%. Has many af you know, sometimes larger images suffer from high compression, but other small images don’t.
This function allows to resample all the jpg images
function custom_jpg_compression($args) {
return 90;
}
add_filter('jpeg_quality', 'custom_jpg_compression');
How to filter by image size?
A very special filter
The
jpeg_quality
filter is a really special one: It gets used in three different cases and you’ve to use the second argument to determine, if you want to use the filter or not.Don’t let it do everything
The main problem for such a special filter is, that it may fire for later actions, if you ain’t remove it – allow it to run after the first check. So we need to get another filter inside
wp_save_image_file()
to check if we want to alter the compression or not. To disable it for another save process, we remove it right before altering the compression.The kool kid
The really odd thing is, that WP uses a default compression of 90% (which is 10% reduced quality) for every save process. This means, that every time you upload/crop/edit an image, you reduce its quality… which is a pain for images that aren’t the best, when you upload them (test it with an image containing a lot of red with a high contrast background). But… The really neat thing is, that you can change this behavior. So you want to change the compression, but get increased quality – much better than core allows- at the same time.
EDIT: After a short discussion with @toscho, he pointed out, that the whole callback could be reduced to the following:
As I pulled the code out of a plugin I’m currently working on, I needed the
switch
to add settings in. I also have to note, that I don’t use theglobal
in my plugin, as it’s an OOP approach. The code you can read â above, is mainly reduced and altered code from the plugin, that has some minor left overs and is meant to be explanatory for later readers and still works. If you want to use it as plugin, you can do some optimization depending on your personal use case.Notes:
From some investigation on the different tasks, there are, I noticed, that multiple
$case
s get triggered on the following steps:edit-image
»image-resize
(the later 1Ã for any any size you choose – Thumbnail, etc.)edit-image
»image-resize
(–“–)This means, that the filter callback for
jpeq_quality
will trigger 2Ã for rotating/mirroring an image and +1Ã for any additional size you add. So if you got less than 100%, it will reduce the quality twice. I did a lot of research on this topic, but I’m still not completely sure, what exact functions cause this behavior.