Last active
September 10, 2015 00:58
-
-
Save listenrightmeow/489b6c9524217cfbbeac to your computer and use it in GitHub Desktop.
Generate responsive image after Media Library upload with Wordpress
This file contains hidden or 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 | |
function create_responsive_images($id) { | |
$file = get_attached_file($id); | |
$image = wp_get_image_editor($file); | |
if (!is_wp_error($image)) { | |
$dimensions = $image->get_size(); | |
$width = $dimensions['width']; | |
$sizes = array(); | |
$measurements = array(0.14, 0.26, 0.28, 0.35, 0.3875, 0.50, 0.52, 0.70, 0.775); | |
foreach ($measurements as $value) { | |
array_push($sizes, array('width' => ceil($width * $value), 'height' => null, 'crop' => false)); | |
} | |
$multi = $image->multi_resize($sizes); | |
$suffix = array('mini', 'small', 'mini-retina', 'medium', 'plus', 'large', 'small-retina', 'medium-retina', 'plus-retina'); | |
$quality = array(60, 60, 40, 50, 40, 50, 40, 30, 30); | |
foreach ($multi as $key => $resize) { | |
$path = ABSPATH . 'wp-content/uploads/' . date('Y') . '/' . date('m') . '/' . $resize['file']; | |
$tmp = wp_get_image_editor($path); | |
$info = pathinfo($path); | |
$filename = explode('-', $info['filename']); | |
$original = $info['dirname'] . '/' . $filename[0] . '-' . $filename[1] . '.' . $info['extension']; | |
$resize = $info['dirname'] . '/' . $filename[0] . '-' . $filename[1] . '-' . $filename[1] . '.' . $info['extension']; | |
$tmp->set_quality($quality[$key]); | |
$tmp->save(); | |
rename($original, $info['dirname'] . '/' . $filename[0] . '-' . $suffix[$key] . '.' . $info['extension']); | |
if (file_exists($original)) unlink($original); | |
if (file_exists($resize)) unlink($resize); | |
} | |
} | |
} | |
add_action('add_attachment', 'create_responsive_images'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment