Skip to content

Instantly share code, notes, and snippets.

@miya0001
Created March 20, 2018 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miya0001/225318c89e4d2516975e5022bdb30156 to your computer and use it in GitHub Desktop.
Save miya0001/225318c89e4d2516975e5022bdb30156 to your computer and use it in GitHub Desktop.
Optimizing images for WordPress with the jpegoptim
<?php
add_filter( 'wp_image_editors', function( $editors ) {
if ( ! class_exists( '_WP_Image_Editor_GD' ) ) {
class _WP_Image_Editor_GD extends WP_Image_Editor_GD {
protected function _save( $image, $filename = null, $mime_type = null ) {
$saved = parent::_save( $image, $filename, $mime_type );
if ( ! empty( $saved["mime-type"] ) && 'image/jpeg' == $saved["mime-type"] ) {
jpegoptim( $saved['path'] );
}
return $saved;
}
};
}
if ( ! class_exists( '_WP_Image_Editor_Imagick' ) ) {
class _WP_Image_Editor_Imagick extends WP_Image_Editor_Imagick {
protected function _save( $image, $filename = null, $mime_type = null ) {
$saved = parent::_save( $image, $filename, $mime_type );
if ( ! empty( $saved["mime-type"] ) && 'image/jpeg' == $saved["mime-type"] ) {
jpegoptim( $saved['path'] );
}
return $saved;
}
};
}
return array(
'_WP_Image_Editor_GD',
'_WP_Image_Editor_Imagick',
);
}, 10 );
function jpegoptim( $path, $quality = 60 ) {
if ( ! is_executable( '/usr/bin/jpegoptim' ) ) {
trigger_error( '`/usr/bin/jpegoptim` is not executable, please install it.' );
return;
}
if ( is_file( $path ) ) {
$cmd = '/usr/bin/jpegoptim -m%d --strip-all %s 2>&1';
$result = exec( sprintf( $cmd, intval( $quality ), escapeshellarg( $path ) ), $output, $status );
if ( $status ) {
trigger_error( $result );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment