Last active
December 18, 2020 18:19
-
-
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]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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
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/