1

We are currently using this to change the compression used on jpgs when uploaded to the WP media library:

add_filter(‘jpeg_quality’, function($arg){return 75;});

However, this does not compress the original image. We sometimes need to display the original image on our website and this also needs to be compressed. How do we do this?

Thanks in advance for any help!

1

For compressing the uploaded image I wrote a simple code snippet that immediately overwrites a newly uploaded file with an image whose quality can be specified:

function wt_handle_upload_callback( $data ) {
    $image_quality = 30; // Change this according to your needs
    $file_path = $data['file'];
    $image = false;

    switch ( $data['type'] ) {
        case 'image/jpeg': {
            $image = imagecreatefromjpeg( $file_path );
            imagejpeg( $image, $file_path, $image_quality );
            break;          
        }

        case 'image/png': {
            $image = imagecreatefrompng( $file_path );
            imagepng( $image, $file_path, $image_quality );
            break;          
        }

        case 'image/gif': {         
            // Nothing to do here since imagegif doesn't have an 'image quality' option
            break;
        }
    }

    return $data;
}
add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' );

Regarding the additional image sizes (just change the return value):

add_filter( 'wp_editor_set_quality', function( $quality ) { return 30; } );
  • This is great code snippet. BUT, on my tests, this function removes all image EXIF/IPTC data too. Can you please modify it to have option to preserve image EXIF data? than I will use it for sure. Thank you @webtoure – Advanced SEO Jan 13 '16 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.