Last active
February 18, 2018 05:38
-
-
Save davidegreenwald/8074ec642c8e9461f8e802f83b2eb88a to your computer and use it in GitHub Desktop.
WordPress function to delete add-on .webp files with their paired attachments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Delete webp files with image attachments | |
*/ | |
/* | |
Make sure to remove .webp files generated by EWWW or manually when their | |
parent .jpg image and thumbnails are deleted. | |
This allows you to wipe the EWWW database table, which bloats quickly. If the db is wiped normally, deleting images will leave orphan .webp files. | |
You can also make .webp files easily with the WebPonize app. | |
*/ | |
function delete_webp_with_img( $attachmentid ) { | |
// check if we have an image being deleted | |
if(isset($attachmentid)) { | |
// get the file path for the image being deleted | |
$img = get_attached_file($attachmentid); | |
// get the file path without the .jpg extension | |
$img_root = preg_replace('/\.jp(e)?g|\.png|\.gif/', '', $img); | |
// look for .webp files matching the path, including all thumbnails! | |
$webp_files = glob($img_root . '*.webp'); | |
// do a foreach loop to delete each one | |
foreach($webp_files as $webp_file) { | |
if(file_exists($webp_file)) { | |
wp_delete_file($webp_file); | |
} | |
} | |
} | |
} | |
add_action( 'delete_attachment', 'delete_webp_with_img' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment