Skip to content

Instantly share code, notes, and snippets.

@retgef
Created October 20, 2012 03:09
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save retgef/3921866 to your computer and use it in GitHub Desktop.
Save retgef/3921866 to your computer and use it in GitHub Desktop.
Remove attachment rows where the associated file on the disk doesn't exist.
<?php
/**
* Usage when logged in: http://yourdomain.com/wp-admin/remove-404-attachments=secretpassword
*/
# Hook late into admin_init
add_action('admin_init', 'remove_404_attachments', 9999999);
function remove_404_attachments(){
# Must be an admin
if(!current_user_can('manage_options'))
return;
# Fire this only when needed
if(!isset($_GET['remove-404-attachmentss']) && $_GET['remove-404-attachments'] === 'secretpassword')
return;
# Run the query
global $wpdb;
$sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment'");
$attachments = $wpdb->get_results($sql);
# Spin cycle
foreach($attachments as $attachment){
# Get the absolute path of the attachment
$file_path = get_attached_file($attachment->ID, true);
# Check if the attachment exits
if(!file_exists($file_path)){
$deleted = wp_delete_attachment($attachment->ID, true);
if($deleted)
show_message("<span style='color:red;'>$file_path Deleted</span>");
else
show_message("<span style='color:yellow;'>Post #$attachment->ID could not be deleted from the database.</span>");
}
else
show_message("<span style='color:green;'>$file_path exists.</span>");
}
exit;
}
@jessedmatlock
Copy link

Some helpful hints..
The URL you have in the comment:

http://yourdomain.com/wp-admin/remove-404-attachments=secretpassword  should be
http://yourdomain.com/wp-admin/index.php?remove-404-attachments=secretpassword  <-- notice the index.php?

You have a typo at : !isset($_GET['remove-404-attachmentss']) --- notice the double 'ss'

Also, the $wpdb->prepare call will fail, as it's incorrectly formatted.
Try this to avoid errors:

    $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_type = %s", $type);
    $attachments = $wpdb->get_results($sql);

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