Skip to content

Instantly share code, notes, and snippets.

@neverything
Last active October 27, 2023 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neverything/06ccf157ef94e25e0be5550ce948a208 to your computer and use it in GitHub Desktop.
Save neverything/06ccf157ef94e25e0be5550ce948a208 to your computer and use it in GitHub Desktop.
WordPress: Strip image metadata on upload to the media library using Imagick. Learn more https://silvanhagen.com/strip-image-meta-data-wordpress/
<?php
add_filter( 'wp_handle_upload', 'yourprefix_strip_metadata_from_images_on_upload' );
function yourprefix_strip_metadata_from_images_on_upload( array $upload ): array {
if ( ! in_array( $upload['type'], array( 'image/jpeg', 'image/png', 'image/gif' ), true ) ) {
return $upload;
}
try {
yourprefix_strip_metadata_from_image( $upload['file'] );
} catch ( \ImagickException $e ) {
// Do nothing.
}
return $upload;
}
function yourprefix_strip_metadata_from_image( string $file, ?string $output = null ) {
$image = new \Imagick( $file );
// Check if we have an ICC profile, so we can restore it later.
$profile = null;
try {
$profile = $image->getImageProfile( 'icc' );
} catch ( \ImagickException $exception ) {
// Raises an exception if no profile is found.
}
// Strip all image metadata.
$image->stripImage();
// Restore the ICC profile if we have one.
if ( ! empty( $profile ) ) {
$image->setImageProfile( 'icc', $profile );
}
if ( empty( $output ) ) {
$output = $file;
}
$image->writeImage( $output );
$image->clear();
$image->destroy();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment