How to change image quality in WordPress

The wp_editor_set_quality filter allows you to change the image quality based on the corresponding mime type.

function stackinstall_filter_wp_editor_set_quality( $quality, $mime_type ) {
   if ( $mime_type === 'image/jpeg' ) {
        $quality = 80;
    } elseif ( $mime_type === 'image/png' ) {
    } elseif ( $mime_type === 'image/gif' ) {
    }
    return $quality;
}

add_filter( 'wp_editor_set_quality', 'stackinstall_filter_wp_editor_set_quality', 10, 2 );

The jpeg_quality filter changes the quality of JPEG images only.

function stackinstall_filter_jpeg_quality( $quality, $context ) {
    if ( $context === 'edit_image' ) {
        $quality = 80;
    } elseif ( $context === 'image_resize' ) {
        $quality = 80;
    }
    return $quality; 
}
 
add_filter( 'jpeg_quality', 'stackinstall_filter_jpeg_quality', 10, 2 );

These two filters run in sequence, first you run the wp_editor_set_quality filter and then the jpeg_quality filter, if you want to change the quality of JPEG images only it is recommended that you use the jpeg_quality filter, if you want to change the quality of PNG images or GIF uses the wp_editor_set_quality filter.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.