Good question, I have a chance to write a small wrapper that basically implements such functionality…
- I was thinking about when I should run my optimization and what exactly I should process files. Ended up in next conclusions…
- The main Image will be changed somewhere later, using wp_cron schedule. Nothing particularly interesting… you taking your file, run it through the optimisation pipeline, and in case
Success
setting param to not optimize it again in post meta, in case offail
mark it asFailed
and forget about image. - With copies it was easier. I just use
wp_update_attachment_metadata
filter $hook to get files list when update metadata was triggered (on image size generation for example).
- The main Image will be changed somewhere later, using wp_cron schedule. Nothing particularly interesting… you taking your file, run it through the optimisation pipeline, and in case
“`
add_filter( 'wp_update_attachment_metadata',
array( __CLASS__, 'optimize_images_in_foreach' ), 100, 2 );
Files Optimization.
/**
* Optimize Copies of imges in loop while images regeneration
*
* @param array $metadata Image Metadata (images, exif data, etc...)
* @param int $attachment_id Attachment id
* @return array
*/
function optimize_images_in_foreach( $metadata, $attachment_id ) {
$original_file = get_attached_file( $attachment_id );
if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
foreach( $metadata['sizes'] as $size => $item )
do_action( 'optimize_image',
str_replace( basename( $original_file ), $item['file'], $original_file ) );
}
}
return $metadata;
}
“`
- As you see I have just run own action for images…
optimize_image
. On first stage it was just wrapper forpngout
andjpegtran
, later it was a bit harder implementation with advanced cron schedules and Kraken service (image optimization).
“`
/**
* Run Image Optimization to Jpeg's and PNG's
* @param string $image IMage Location in filesystem
* @return void
*/
function optimize_images_in_foreach_jpeg_png_optimization( $image ) {
$extension = array_pop(explode( '.', basename( $image ) ) );
// `images_optimization` is global option that holds a cli command for image optimization
// examples...
// 'png' => /opt/local/bin/optipng = '{$image}',
// 'jpeg' => /opt/local/bin/jpegtran -copy none -maxmemory 256Mb -optimize \
// -outfile '{$image}' '{$image}'
$optimization = get_site_option('images_optimization');
if ( in_array($extension, array( 'jpeg', 'jpg' ) ) ) {
$type="jpeg";
} elseif ( in_array( $extension, array( 'png' ) ) ) {
$type="png";
} else {
$type="default";
}
if ( ! empty( $optimization[ $type ] ) ) {
$optimization[$type] = str_replace( '{$image}', $image, $optimization[ $type ] );
// execute is a pipline to exec in this itteration.
execute( "{$optimization[$type]}" );
}
}
“`
P.S.
I beg a pardon for a code formatting… it’s failing to work without ““`”