Wordpress - Automatically replace original uploaded image with large image size

Add this to the functions.php file in the theme folder. It replaces the original image with the large image set in settings. You might want to setup a new image format and use that as the new original size though.

function replace_uploaded_image($image_data) {
      // if there is no large image : return
  if (!isset($image_data['sizes']['large'])) return $image_data;

  // paths to the uploaded image and the large image
  $upload_dir = wp_upload_dir();
  $uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
  // $large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file']; // ** This only works for new image uploads - fixed for older images below.
  $current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
  $large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];

  // delete the uploaded image
  unlink($uploaded_image_location);

  // rename the large image
  rename($large_image_location,$uploaded_image_location);

  // update image metadata and return them
  $image_data['width'] = $image_data['sizes']['large']['width'];
  $image_data['height'] = $image_data['sizes']['large']['height'];
  unset($image_data['sizes']['large']);

  return $image_data;
}

add_filter('wp_generate_attachment_metadata','replace_uploaded_image');

There's one nasty bug in the solution above. The solution works as a charm for new images, but for old images, you should never compare to $upload_dir['path'] because that's the current upload folder of the current month.

Replace the following:

//$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];
$large_image_location = $upload_dir['basedir'] . '/'.$image_data['sizes']['large']['path'];

May I suggest an update to the code of the above answer? Unfortunately in newer versions of Wordpress the key 'path' is no longer provided for the file sizes. So to make it work on older post uploads, we should first get the current subdir from the original image and use this to make the location path for the large image.

So replace this line:

$large_image_location = $upload_dir['basedir'] . '/'.$image_data['sizes']['large']['path'];

by these 2 lines:

$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];

Tags:

Images