-
-
Save waqasy/19a97f25d8106d44f195c03da0bcfeab to your computer and use it in GitHub Desktop.
Optimizing images for WordPress with the jpegoptim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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