wordpress, hand, logo-589121.jpg

WordPress resize Image after Upload

For a larger WordPress site it is important to reduce the uploaded image size. Because with lots of auto generated alternative image sizes, webp alternatives, etc one image will be saved multiple times on the server. My ideal workflow is to have a local full-size copy and only upload a shrinked version to WordPress. This snippet automates that process for you. No need to keep multiple copies of the file!

I currently ain’t got time to describe the snippet, but it should be pretty self explaining. You can add it with code snippets, see the section below. There is also a plugin that does this job for you, however I personally prefer this small and clean snippet.

// Hook the function to the upload handler
// https://developer.wordpress.org/reference/hooks/wp_handle_upload/
add_filter('wp_handle_upload', 'resize_image_after_upload');

function resize_image_after_upload($image_data){
  // Set to null to disable that width/height resizing
  $max_width  = 1920;
  $max_height = 1920;

  // Check if there is a valid file
  if(empty($image_data['file']) || empty($image_data['type'])) {
    return $image_data;
  }

  // NOTE: We are not resizing any gifs, to avoid resizing animated gifs
  //      (which I think is the most common gif nowadays)
  $valid_types = array('image/png','image/jpeg','image/jpg', 'image/webp');
  if(!in_array($image_data['type'], $valid_types)) {
    return $image_data;
  }

  // Get image image_editor
  // https://developer.wordpress.org/reference/classes/wp_image_editor/
  $image_editor = wp_get_image_editor($image_data['file']);
  if(is_wp_error($image_editor)) {
    return $image_data;
  }

  // Check if the image editor supports the image type
  if(!$image_editor->supports_mime_type($image_data['type'])) {
    return $image_data;
  }

  // Perform resizing
  $sizes = $image_editor->get_size();
  if((isset($sizes['width']) && $sizes['width'] > $max_width)
    || (isset($sizes['height']) && $sizes['height'] > $max_height)) {
    // Resize, but do not crop
    $image_editor->resize($max_width, $max_height, false);

    // We will use the default recommended image quality
    // Change, if you want to set a custom quality
    //$image_editor->set_quality(90);

    $image_editor->save($image_data['file']);
  }

  return $image_data;
}
Code language: PHP (php)

Continue reading

Buy Me A Coffee

1 thought on “WordPress resize Image after Upload”

Leave a Comment

Your email address will not be published. Required fields are marked *