Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.