Created
August 3, 2015 20:01
-
-
Save ethanhinson/4ab22eabbc26d075dfa7 to your computer and use it in GitHub Desktop.
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 | |
/* | |
Plugin Name: BT Image Optimization | |
Plugin URI: http://bluetent.com | |
Description: Provides image optimization capabilities as users upload images to the library. | |
Author: ethan@bluetent.com | |
Version: 0.1 | |
Author URI: http://bluetent.com/ | |
Text Domain: bt-image-optimize | |
License: GPLv2 | |
*/ | |
class BTImageOptimize { | |
public function __construct() { | |
add_action('add_attachment', array($this, 'attachment_optimize')); | |
} | |
/** | |
* Performs extra processing on images. | |
* @param $id int attachment_id | |
*/ | |
public function attachment_optimize($id) { | |
$sizes = get_intermediate_image_sizes(); | |
$sizes[] = 'full'; | |
foreach($sizes as $size) { | |
$img_src = wp_get_attachment_image_src($id, $size); | |
$real_path = ABSPATH . ltrim(str_replace(get_bloginfo('url'), '', $img_src[0]), '/'); | |
$image_info = getimagesize($real_path); | |
$p = escapeshellarg($real_path); | |
$cmd = "cd " . escapeshellarg(ABSPATH) . "; "; | |
switch($image_info['mime']) { | |
case 'image/png': | |
$cmd .= "/usr/local/bin/optipng $p"; | |
break; | |
case 'image/jpeg': | |
$cmd .= "/usr/local/bin/jpegoptim -p -m70 --strip-all $p"; | |
break; | |
} | |
if(!empty($cmd)) { | |
$output = shell_exec($cmd); | |
} | |
} | |
} | |
} | |
$BTImageOptimize = new BTImageOptimize(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment