diff --git a/html/modules/custom/reliefweb_utility/reliefweb_utility.module b/html/modules/custom/reliefweb_utility/reliefweb_utility.module
index 6178839b5..64f77375f 100644
--- a/html/modules/custom/reliefweb_utility/reliefweb_utility.module
+++ b/html/modules/custom/reliefweb_utility/reliefweb_utility.module
@@ -89,3 +89,23 @@ function reliefweb_utility_file_presave(FileInterface $file) {
}
}
}
+
+/**
+ * Implements hook_entity_type_alter().
+ *
+ * Replace the image style class so we can properly delete webp versions of the
+ * derivative images because this is not done by image_optimize_webp, notably
+ * because there is no hook provided for that by the image module.
+ *
+ * Normally this runs after the imageapi_optimize_entity_type_alter() due to
+ * the alphabetical order.
+ */
+function reliefweb_utility_entity_type_alter(array &$entity_types) {
+ /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
+ if (isset($entity_types['image_style'])) {
+ $image_style = $entity_types['image_style'];
+ if ($image_style->getClass() === 'Drupal\imageapi_optimize\Entity\ImageStyleWithPipeline') {
+ $image_style->setClass('Drupal\reliefweb_utility\Entity\ImageStyleWithPipeline');
+ }
+ }
+}
diff --git a/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php b/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php
new file mode 100644
index 000000000..9a2492d0c
--- /dev/null
+++ b/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php
@@ -0,0 +1,39 @@
+buildUri($path);
+ $derivative_uri_webp = $derivative_uri . '.webp';
+
+ if (file_exists($derivative_uri_webp)) {
+ try {
+ $file_system->delete($derivative_uri_webp);
+ }
+ catch (FileException $exception) {
+ // Ignore failed deletion.
+ }
+ }
+ }
+
+ return $result;
+ }
+
+}