The jpeg_quality WordPress PHP Filter allows you to change the JPEG compression quality for backward compatibility.
Usage
add_filter('jpeg_quality', 'your_custom_function', 10, 2); function your_custom_function($quality, $context) { // your custom code here return $quality; }
Parameters
- $quality (int): Quality level between 0 (low) and 100 (high) of the JPEG.
- $context (string): Context of the filter, can be either ‘image_resize’ or ‘edit_image’.
More information
See WordPress Developer Resources: jpeg_quality
Examples
Increase JPEG quality to 90
Increase the JPEG quality to 90 for both resizing and editing images.
add_filter('jpeg_quality', 'increase_jpeg_quality', 10, 2); function increase_jpeg_quality($quality, $context) { $quality = 90; return $quality; }
Set different JPEG quality for resizing and editing
Set the JPEG quality to 80 for image resizing and 90 for image editing.
add_filter('jpeg_quality', 'set_different_jpeg_quality', 10, 2); function set_different_jpeg_quality($quality, $context) { if ($context == 'image_resize') { $quality = 80; } elseif ($context == 'edit_image') { $quality = 90; } return $quality; }
Decrease JPEG quality based on user role
Decrease the JPEG quality to 70 for users with the ‘subscriber’ role.
add_filter('jpeg_quality', 'decrease_jpeg_quality_for_subscribers', 10, 2); function decrease_jpeg_quality_for_subscribers($quality, $context) { if (current_user_can('subscriber')) { $quality = 70; } return $quality; }
Increase JPEG quality for specific image sizes
Increase the JPEG quality to 95 for ‘large’ image sizes.
add_filter('jpeg_quality', 'increase_jpeg_quality_for_large_images', 10, 2); function increase_jpeg_quality_for_large_images($quality, $context) { $size = 'large'; if ($context == 'image_resize' && $size == 'large') { $quality = 95; } return $quality; }
Set JPEG quality based on custom image sizes
Set the JPEG quality based on custom image sizes registered with add_image_size
.
add_filter('jpeg_quality', 'set_jpeg_quality_based_on_custom_sizes', 10, 2); function set_jpeg_quality_based_on_custom_sizes($quality, $context) { global $_wp_additional_image_sizes; if (isset($_wp_additional_image_sizes['custom_size'])) { $custom_size_quality = 85; $quality = $custom_size_quality; } return $quality; }