# Protect Featured Images From Deletion

> Stops anyone from permanently deleting an image while it is still the featured image of a post or page, and shows which post uses it, so articles never end up with a missing picture.

- Type: PHP
- Runs: Run everywhere
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: media-library, featured-image, safety
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/media-protect-images-in-use/

## Code

```php
add_filter( 'pre_delete_attachment', function ( $delete, $post ) {
    global $wpdb;

    if ( ! $post instanceof WP_Post || 'attachment' !== $post->post_type ) {
        return $delete;
    }

    $used_by = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT pm.post_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = %d AND p.post_status NOT IN ('trash','auto-draft') AND p.post_type <> 'revision' LIMIT 1",
        $post->ID
    ) );

    if ( ! $used_by ) {
        return $delete;
    }

    if ( wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
        return false; // The deletion simply fails.
    }

    wp_die(
        esc_html( sprintf( 'This image is the featured image of "%s". Choose another featured image before deleting it.', get_the_title( $used_by ) ) ),
        'Image in use',
        array( 'response' => 409, 'back_link' => true )
    );
}, 10, 2 );
```

## Notes

Remove the image as featured image first (or use another), then it can be deleted.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Protect Featured Images From Deletion" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
