Skip to content

Instantly share code, notes, and snippets.

@joshuafredrickson
Created February 12, 2019 16:05
Show Gist options
  • Save joshuafredrickson/c8b3819d9d6ec7326c4955c39ac79787 to your computer and use it in GitHub Desktop.
Save joshuafredrickson/c8b3819d9d6ec7326c4955c39ac79787 to your computer and use it in GitHub Desktop.
WordPress: Generate @2x image sizes automatically.
<?php
/**
* @2x image sizes
*/
function make_it_retina($file, $width, $height, $crop = false) {
if ($width || $height) {
$resized_file = wp_get_image_editor($file);
if (!is_wp_error($resized_file)) {
$resized_file->resize($width * 2, $height * 2, $crop);
$filename = $resized_file->generate_filename($width . 'x' . $height . '@2x');
$resized_file->save($filename);
}
if (!is_wp_error($resized_file) && $resized_file && $info = getimagesize($filename)) {
$filename = apply_filters('scout_make_it_retina', $filename);
return [
'file' => wp_basename($filename),
'width' => $info[0],
'height' => $info[1],
];
}
}
return false;
}
add_filter('wp_generate_attachment_metadata', function ($metadata, $attachment_id) {
$attachment = get_post($attachment_id);
$file = get_attached_file($attachment_id);
$old_metadata = $metadata;
foreach ($metadata as $k => $v) {
if (is_array($v)) {
foreach ($v as $key => $val) {
if (is_array($val)) {
\App\make_it_retina($file, $val['width'], $val['height'], true);
}
}
}
}
return $old_metadata;
}, 10, 2);
add_filter('delete_attachment', function ($attachment_id) {
$metas = wp_get_attachment_metadata($attachment_id);
$updir = wp_upload_dir();
$path = pathinfo($metas['file']);
$path_name = $path['dirname'];
$updir = wp_upload_dir();
foreach ($metas as $meta => $meta_val) {
if ($meta === 'sizes') {
foreach ($meta_val as $sizes => $size) {
$original_filename = $updir['basedir'] . '/' . $path_name . '/' . $size['file'];
$x2_filename = substr_replace($original_filename, '@2x.', strrpos($original_filename, '.'), strlen('.'));
if (file_exists($x2_filename)) {
unlink($x2_filename);
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment