Created
October 20, 2012 03:09
-
-
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.
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
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some helpful hints..
The URL you have in the comment:
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: