Forked from sabrina-zeidan/delete_404_attachments.php
Created
February 6, 2022 07:58
-
-
Save vevgeniy85/c3160da26691f9bd653f91223095459c to your computer and use it in GitHub Desktop.
Clean Media Library from broken images. Delete attachments which files no longer available and return 404 error [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_404_attachments(){ | |
$attachments = get_posts( array( | |
'post_type' => 'attachment', | |
'numberposts' => -1, | |
'fields' => 'ids' | |
)); | |
if ($attachments) { | |
foreach ($attachments as $attachmentID){ | |
$file_url = wp_get_attachment_url( $attachmentID); | |
$file_headers = @get_headers($file_url); | |
if($file_headers[0] == 'HTTP/1.1 404 Not Found') { | |
$deleted = wp_delete_attachment($attachmentID, true); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment