My goal is to make a retina and non-retina image when user uploads a photo. This is doable like so:

add_action('init', function() {
    // Get the original image sizes and duplicate
    $thumb_w = get_option('thumbnail_size_w') * 2;
    $thumb_h = get_option('thumbnail_size_h') * 2;
    $thumb_crop = get_option('thumbnail_crop');
    $medium_w = get_option('medium_size_w') * 2;
    $medium_h = get_option('medium_size_h') * 2;
    $large_w = get_option('large_size_w') * 2;
    $large_h = get_option('large_size_h') * 2;

    // Register the actual sizes
    add_image_size('thumbnail-retina', $thumb_w, $thumb_h, $thumb_crop);
    add_image_size('medium-retina', $medium_w, $medium_h);
    add_image_size('large-retina', $large_w, $large_h);

This is good, but the most optimal would be to chop half the full image, then use the original as the retina and the new as non-retina.

Here's my rationale on it:

  1. Intercept the image upload process with a hook, add_attachment
  2. Measure the img and chop half with wp_get_image_editor
  3. Suffix it with "1x"
  4. Save the new image

What I have so far (this works, but it's a bit faulty):

add_filter('add_attachment', function ($attachment_id) {
    $src = get_attached_file($attachment_id);

    if (!$src) {

    $img_info = pathinfo($src);
    $image_editor = wp_get_image_editor($src);

    // Get image sizes
    $size = $image_editor->get_size($src);
    $width = $size['width'];
    $height = $size['height'];

    // Chop the image in half and save
    $image_editor->resize($width / 2, $height / 2, false);

    return $attachment_id;

}, 10, 2);

How does that look to you, am I doing it right?

The fault is: WordPress doesn't know anything about the new 1x image, so when the image is deleted, the 1x copy stays behind. Any ideas how to approach that?

Here's a similar post, but it doesn't really deal with the full image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.