I have the website on wordpress
and function replace_uploaded_image in functions.php which uploads images from external url and transforms their original sizes to thumbnail sizes.
But I wouldn’t like to made this transformations when I directly upload images in admin library.
What condition do I need to supplement the function or on which hook to hang?
function replace_uploaded_image($image_data) {
if (!isset($image_data['sizes']['thumbnail'])) return $image_data;
// paths to the uploaded image and the thumbnail image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$thumbnail_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['thumbnail']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the thumbnail image
rename($thumbnail_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['thumbnail']['width'];
$image_data['height'] = $image_data['sizes']['thumbnail']['height'];
unset($image_data['sizes']['thumbnail']);
return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
2
Answers
To resolve this issue first I was need to add second parametr
$attachment_id
to function replace_uploaded_image and then find out if the attachment haspost_author
.Full code:
You can add a condition that checks whether the image’s metadata contains a post_parent value. This value is only set when an image is uploaded via the admin panel. The post_parent value, the function can determine whether an image was uploaded via the admin panel or not, and only modify images that were uploaded from external URLs.
Here’s the modified code:
The function will only modify images that were uploaded from external URLs and not via the admin panel.