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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.