Remove Location and Camera Data From Uploaded Photos
Strips EXIF metadata such as GPS location, camera serial number and date from JPEG and WebP images when they are uploaded, while keeping them correctly rotated.
Opens WPIDE on
Code
add_filter( 'wp_handle_upload', function ( $upload ) {
if ( empty( $upload['file'] ) || empty( $upload['type'] ) || ! in_array( $upload['type'], array( 'image/jpeg', 'image/webp' ), true ) || ! is_writable( $upload['file'] ) ) {
return $upload;
}
$file = $upload['file'];
if ( class_exists( 'Imagick' ) ) {
try {
$image = new Imagick( $file );
switch ( $image->getImageOrientation() ) {
case Imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateImage( '#000', 180 );
break;
case Imagick::ORIENTATION_RIGHTTOP:
$image->rotateImage( '#000', 90 );
break;
case Imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateImage( '#000', -90 );
break;
}
$image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT );
$profiles = $image->getImageProfiles( 'icc', true );
$image->stripImage();
if ( ! empty( $profiles['icc'] ) ) {
$image->profileImage( 'icc', $profiles['icc'] );
}
$image->writeImage( $file );
$image->clear();
} catch ( Exception $e ) {
return $upload;
}
return $upload;
}
// GD fallback: re-saving drops all metadata.
if ( 'image/jpeg' === $upload['type'] && function_exists( 'imagecreatefromjpeg' ) ) {
$exif = function_exists( 'exif_read_data' ) ? @exif_read_data( $file ) : false; // Corrupt EXIF blocks raise warnings.
$orientation = is_array( $exif ) && ! empty( $exif['Orientation'] ) ? (int) $exif['Orientation'] : 1;
$image = @imagecreatefromjpeg( $file );
if ( $image ) {
$angles = array( 3 => 180, 6 => -90, 8 => 90 );
if ( isset( $angles[ $orientation ] ) ) {
$image = imagerotate( $image, $angles[ $orientation ], 0 );
}
imagejpeg( $image, $file, 90 );
imagedestroy( $image );
}
}
return $upload;
} );
Notes
Uses Imagick when available and falls back to re-saving with GD (which also removes color profiles); photographers who want to keep metadata should not use this.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.