Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.