Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active December 18, 2020 18:19
Show Gist options
  • Save sabrina-zeidan/1c8b86954112b667d731c2b5c29947e3 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/1c8b86954112b667d731c2b5c29947e3 to your computer and use it in GitHub Desktop.
Delete orhaned attachments which are not attached to any post, page or cpt [Wordpress]
function delete_unattached_attachments(){
$attachments = get_posts( array(
'post_type' => 'attachment',
'numberposts' => -1,
'fields' => 'ids',
'post_parent' => 0,
));
if ($attachments) {
foreach ($attachments as $attachmentID){
$attachment_path = get_attached_file( $attachmentID);
//Delete attachment from database only, not file
$delete_attachment = wp_delete_attachment($attachmentID, true);
//Delete attachment file from disk
$delete_file = unlink($attachment_path);
}
}
}
@jeffdaigle
Copy link

Thanks for posting this! One revision I'd suggest is to use wp_delete_file() instead of unlink() on line 14. wp_delete_file() filters the input and makes it more reliable/less dangerous: https://developer.wordpress.org/reference/functions/wp_delete_file/

@halleg
Copy link

halleg commented Dec 18, 2020

Thanks for this. A use case for you: with RSS feed aggregators this script is essential as when you scale you need to clean the tail of the unwanted post you syndicated. Would be nice to have it follow some patterns to avoid removing files from Elementor as now it could happen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment