Benny29390
7/24/2017 - 2:22 PM

Remove attachment rows where the associated file on the disk doesn't exist.

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;
}