What you want is probably something like this.
You need to manually unlink the original image including added sizes.
The WP image editor automatically creates a new image with a new name as you mentioned but not others added through add_image_size()
function.
regenerate_added_sizes()
in the code below does exactly that:
function replace_original_images( $override, $filename, $image, $mime_type, $post_id ) {
if ( 'image/jpeg' !== $mime_type && 'image/png' !== $mime_type ) {
return $override;
}
$image_meta = wp_get_attachment_metadata( $post_id );
$upload_dir = wp_upload_dir();
$original_file_path = path_join( $upload_dir['basedir'], $image_meta['file'] );
// 'full dir' includes year and mouth location
$upload_full_dir = str_replace( basename( $original_file_path ), '', $original_file_path );
// delete original image
unlink( $original_file_path );
// delete other sizes
foreach ( $image_meta['sizes'] as $size ) {
unlink( $upload_full_dir . $size['file'] );
}
// regenerate added sizes
function regenerate_added_sizes( $meta_id, $object_id, $meta_key ) {
if ( '_wp_attachment_metadata' !== $meta_key ) {
return;
}
$image_meta = wp_get_attachment_metadata( $object_id );
$upload_dir = wp_upload_dir();
$new_file_path = path_join( $upload_dir['basedir'], $image_meta['file'] );
// prevent infinite loops
remove_action( 'updated_post_meta', 'regenerate_added_sizes' );
update_post_meta( $object_id, $meta_key, wp_generate_attachment_metadata( $object_id, $new_file_path ) );
}
add_action( 'updated_post_meta', 'regenerate_added_sizes', 10, 3 );
return $override;
}
add_filter( 'wp_save_image_editor_file', 'replace_original_images', 10, 5 );