Home / Admin / Unattached Media Cleanup
Duplicate Snippet

Embed Snippet on Your Site

Unattached Media Cleanup

Code Preview
php
<?php
// Schedule the event if it is not already scheduled
function schedule_unattached_media_cleanup() {
    if (!wp_next_scheduled('delete_unattached_media_event')) {
        wp_schedule_event(time(), 'daily', 'delete_unattached_media_event');
    }
}
add_action('wp', 'schedule_unattached_media_cleanup');
// Hook the function to the scheduled event
add_action('delete_unattached_media_event', 'delete_unattached_media');
// Function to delete unattached media
function delete_unattached_media() {
    global $wpdb;
    // Get all unattached media files (post_parent = 0)
    $attachments = $wpdb->get_results(
        "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_parent = 0"
    );
    $deleted_count = 0;
    foreach ($attachments as $attachment) {
        // Delete the unattached media file
        wp_delete_attachment($attachment->ID, true);
        $deleted_count++;
    }
    // Optional: Log the deletion count (for debugging purposes)
    error_log("Deleted $deleted_count unattached media files.");
}

Comments

Add a Comment