Using WordPress ‘delete_attachment’ PHP action

The delete_attachment WordPress PHP action fires before an attachment is deleted, at the start of wp_delete_attachment().

Usage

add_action('delete_attachment', 'your_function_name');
function your_function_name($post_id) {
    // your custom code here
}

Parameters

  • $post_id (int) – Attachment ID.

More information

See WordPress Developer Resources: delete_attachment

Examples

Log Attachment Deletion

Log attachment deletion in a custom log file.

add_action('delete_attachment', 'log_attachment_deletion');
function log_attachment_deletion($post_id) {
    $log_message = "Attachment with ID {$post_id} has been deleted.";
    error_log($log_message, 3, '/path/to/your/custom_log.log');
}

Notify Admin on Attachment Deletion

Send an email notification to the admin when an attachment is deleted.

add_action('delete_attachment', 'notify_admin_on_attachment_deletion');
function notify_admin_on_attachment_deletion($post_id) {
    $admin_email = get_option('admin_email');
    $subject = "Attachment Deleted";
    $message = "An attachment with ID {$post_id} has been deleted.";
    wp_mail($admin_email, $subject, $message);
}

Remove Attachment Metadata

Remove attachment metadata when an attachment is deleted.

add_action('delete_attachment', 'remove_attachment_metadata');
function remove_attachment_metadata($post_id) {
    delete_post_meta($post_id, '_wp_attachment_metadata');
}

Update Post Count on Attachment Deletion

Update the post count when an attachment is deleted.

add_action('delete_attachment', 'update_post_count_on_attachment_deletion');
function update_post_count_on_attachment_deletion($post_id) {
    $post = get_post($post_id);
    $parent_id = $post->post_parent;
    if ($parent_id) {
        $attachments_count = get_post_meta($parent_id, 'attachments_count', true);
        $attachments_count = ($attachments_count > 0) ? $attachments_count - 1 : 0;
        update_post_meta($parent_id, 'attachments_count', $attachments_count);
    }
}

Delete Associated Image Sizes

Delete all associated image sizes when an attachment is deleted.

add_action('delete_attachment', 'delete_associated_image_sizes');
function delete_associated_image_sizes($post_id) {
    $metadata = wp_get_attachment_metadata($post_id);
    if ($metadata && isset($metadata['sizes'])) {
        $upload_dir = wp_upload_dir();
        foreach ($metadata['sizes'] as $size => $file_info) {
            $file_path = $upload_dir['basedir'] . '/' . dirname($metadata['file']) . '/' . $file_info['file'];
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }
    }
}