Using WordPress ‘pre_delete_attachment’ PHP filter

The pre_delete_attachment filter lets you control if an attachment should be deleted, or if it should be bypassed before the deletion takes place.

Usage

add_filter('pre_delete_attachment', 'your_custom_function', 10, 3);

function your_custom_function($delete, $post, $force_delete) {
    // your custom code here
    return $delete;
}

Parameters

  • $delete (WP_Post|false|null) – Whether to proceed with deletion or not.
  • $post (WP_Post) – The post object representing the attachment.
  • $force_delete (bool) – Whether to bypass the Trash or not.

More information

See WordPress Developer Resources: pre_delete_attachment

Examples

Prevent Deletion of PDF Attachments

This example prevents the deletion of any PDF attachments in your WordPress site.

add_filter('pre_delete_attachment', 'prevent_pdf_deletion', 10, 3);

function prevent_pdf_deletion($delete, $post, $force_delete) {
    if ('application/pdf' === $post->post_mime_type) {
        return false;
    }
    return $delete;
}

Allow Deletion Only for Administrators

This example allows only administrators to delete attachments.

add_filter('pre_delete_attachment', 'allow_admin_only_deletion', 10, 3);

function allow_admin_only_deletion($delete, $post, $force_delete) {
    if (!current_user_can('administrator')) {
        return false;
    }
    return $delete;
}

Bypass Trash for Image Attachments

This example forces image attachments to be deleted permanently without going to the Trash.

add_filter('pre_delete_attachment', 'bypass_trash_for_images', 10, 3);

function bypass_trash_for_images($delete, $post, $force_delete) {
    if (0 === strpos($post->post_mime_type, 'image/')) {
        return null;
    }
    return $delete;
}

Send Email Notification Before Deleting Attachments

This example sends an email notification to the administrator before deleting an attachment.

add_filter('pre_delete_attachment', 'email_before_deletion', 10, 3);

function email_before_deletion($delete, $post, $force_delete) {
    $admin_email = get_option('admin_email');
    $subject = "Attachment Deleted: {$post->post_title}";
    $message = "The following attachment has been deleted: {$post->post_title} (ID: {$post->ID})";

    wp_mail($admin_email, $subject, $message);

    return $delete;
}

Log Attachment Deletion

This example logs the deletion of an attachment in a custom log file.

add_filter('pre_delete_attachment', 'log_attachment_deletion', 10, 3);
function log_attachment_deletion($delete, $post, $force_delete) {
$log_file = WP_CONTENT_DIR . '/deletion_log.txt';
$log_entry = date('Y-m-d H:i:s') . " - Attachment Deleted: {$post->post_title} (ID: {$post->ID})" . PHP_EOL;

file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);

return $delete;
}