Skip to content

Instantly share code, notes, and snippets.

@BruceMcKinnon
Created October 24, 2022 23:43
Show Gist options
  • Save BruceMcKinnon/3b54e17ca746efc5c2bb879e61816f00 to your computer and use it in GitHub Desktop.
Save BruceMcKinnon/3b54e17ca746efc5c2bb879e61816f00 to your computer and use it in GitHub Desktop.
Block high-resolution JPGs being uploaded to the Wordpress Media Library
//
// Block high-res JPGs (e.g., direct photos direct from the camera) being uploaded to the Wordpress Media Library
//
// Add this to the themes functions.php file - If an image is a JPG larger than 500kb then we block it but also alert the
// user if the image is higher than 96dpi.
// The file may be uploaded regardless if the file size is smaller than 500kb.
//
function ingeni_media_library_upload_filter( $file ) {
$is_allowed = true;
// Limit file sizes to 500k for JPGs
$max_jpg_size = 500;
// Limit DPI
$max_dpi = 96;
$preferred_dpi = 72;
// Limit x or y dimensions
$max_dimension = 4000;
// Let's put some limit around uploaded JPGs - no photos direct from the camera allowed.
if ( ( $file['size'] > ( $max_jpg_size * 1024 ) ) && ( $file['type'] == 'image/jpeg' ) ) {
// The file is > 500k
$is_allowed = false;
$file['error'] = 'JPG images must be smaller than '.$max_jpg_size.'k';
// Grab the EXIF data
$exif = exif_read_data( $file['tmp_name'], 'IFD0');
// Only check the X resolution for DPI
if ( array_key_exists('XResolution', $exif) ) {
$x_dpi = $exif['XResolution'];
if ( !is_numeric( $x_dpi ) ) {
$x_dpi = floatval( $x_dpi );
}
$x_dpi = intval( $x_dpi );
if ( $x_dpi > $max_dpi ) {
$is_allowed = false;
$file['error'] = 'This is a high resolution image ['.$x_dpi.'dpi]. It must be reduced to '.$preferred_dpi.'dpi using an image editor like PhotoShop or Paint.NET';
}
}
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'ingeni_media_library_upload_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment