apply_filters( ‘wp_delete_file’, string $file )

Filters the path of the file to delete.


Path to the file to delete.


$delete = apply_filters( 'wp_delete_file', $file );



User Contributed Notes

  1. Skip to note 2 content

    Here’s a quick one-liner using this filter that I wrote for a site that serves .webp images as well as whatever jpeg or png was uploaded to WordPress. When any image file is deleted, it also deletes the .webp version, if it exists. e.g. when you delete an image such as /uploads/2024/01/example.png from the Media Library, it will also delete /uploads/2024/01/example.webp.

    /* When image files are deleted, also delete the .webp version, when it exists */
    add_filter( 'wp_delete_file', function ( string $file ): string {
      return preg_replace_callback( '/^(.+\.)(?:bmp|gif|jpe?g|pdf|png)$/i', function ( array $matches ): string {
        wp_delete_file( $matches[1] . 'webp' );
        return $matches[0];
      }, $file );
    } );

You must log in before being able to contribute a note or feedback.