I used the wordpress import tool to import a file and downloaded the attachments included. After a successful importation, I discovered that my media library only contains 3 file. After hours of research with no solution, I checked the database and discovered that there were only 3 rows with the type 'attachment' which were the files showing in the media library. However, all the files in wp-content/uploads are completely intact.

Is there any way I can restore attachment probably by scanning every file in the wp-content/uploads directory and adding the necessary file back to database?

1 Answer 1


Yes, you can do this. First set up a loop that loops through all the images in the upload directory. Then construct an array with the required data needed to create a new post of the type attachment:

$dir = new DirectoryIterator(wp_upload_dir()[0]);
foreach ($dir as $maybeFile) {
    if ($maybeFile->isFile()) {
        $filename = $maybeFile->getPathname();
        $wp_filetype = wp_check_filetype( $filename, null );
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => sanitize_file_name( $filename ),
            'post_content' => '',
            'post_status' => 'inherit'
        $attach_id = wp_insert_attachment( $attachment, $filename );
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
        wp_update_attachment_metadata( $attach_id, $attach_data );

I used the DirectoryIterator php class: https://www.php.net/manual/en/class.directoryiterator.php

And this other stack overflow answer about how to upload an image that is at an arbitrary url to your upload directory: Programmatically adding images to media library

  • The code has some error. There is no such index as 0 in wp_upload_dir() result. Also, I was hoping that there would be an option to scan over multiple folder such as 2022/09, 2022/10, 2022/11 and so on to find all missing files. Commented Nov 26, 2022 at 8:34
  • I have found a plugin that provides a solution to this issue. The plugin is called Media Sync Commented Nov 26, 2022 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.