2

I wrote a plugin that allows a user to upload a .zip file and then if that file already is in the uploads folder it will erase the contents, upload the new zip file there, and then unzip it.

The plugin works and everything, but I'm noticing that every time I upload a file, it stays in the media library, even though it's deleted from the uploads folder. So the uploads folder could be empty, but it's still showing in the media library. Here's my code to replace the file:

 //first, check if there's an existing directory
      if (file_exists($upload_dir . "PDF-archive")){
          //if the directory exists, delete all the files inside
            $file_names = glob($upload_dir . "PDF-archive/*");
            foreach ($file_names as $files){
              if (is_file($files)){
                unlink($files);
                }
              }
          }
      else {
       //if directory doesn't exist, create a new one
         $pdf_archive_dir = $temp['basedir'];
         $pdf_archive_dir = $pdf_archive_dir . '/PDF-archive';
         wp_mkdir_p($pdf_archive_dir);
       }
      //directory is created and empty, now add files and unzip them
      rename($uploaded_file_path, $new_file_path); //move zip files into new directory
      unzip_zips($uploaded_file_name); //unzips the uploaded file
      }

I'm assuming the media library saves to the database...would there be a way to make sure it gets deleted from there as well? Like I said it works but the client is going to be adding a new zip file every single day so I want to avoid having 50+ entries in the media library, even though they don't exist in the uploads folder.

Sidenote: I'm pretty new to this so if you see issues with my code, I'd appreciate the feedback. Thanks!

3

Wordpress saves media library in the _posts table - you'll see post_type of attachment for media library items. You'll notice a guid value in the row, which is the media items default URL.

While unlink()'ing your file, you can make the file's full URL. Then use that full URL in a simple database query ($wpdb) stating WHERE guid = '$thefullURL'. That will return the row, and you'll be able to get the ID of the media library item.

With ID retrieved you can then delete it with Wordpress's wp_delete_post() (which will delete from library and also a bunch of _postmeta jargon)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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