Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active February 8, 2024 07:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sabrina-zeidan/efafd952f2453edf4a6471d09cdfa747 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/efafd952f2453edf4a6471d09cdfa747 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]
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);
}
}
}
}
@sprocker
Copy link

sprocker commented Dec 18, 2017

Not used anything like this before - where would I add this? to the funcitons.php file? then how would I run it?

@mgip
Copy link

mgip commented Mar 31, 2020

good question

@FarhangQ
Copy link

FarhangQ commented Feb 8, 2024

You can action init.

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