I work on a plugin that gets a file uploaded to the upload folder through media. The file is processed if it does not meet x condition the process is aborted and the file is deleted.

The deletion is effective when invoking unlink in this way

if ($counter === 0) {
    printMessage('No need to process');

    if (unlink($file)) {
        printMessage('File removed');


Here $file is a reference to wp_handle_upload $upload['file']

My case is that after verifying that the file has indeed been deleted from the file system, there is a reference to it in the media library.

enter image description here

I appreciate your comments


When you upload a file to Media Library, some data (mainly metadata like title, description, and so on) is stored in database.

So if you delete file using unlink, you don't delete any rows from DB - so the attachment will be still visible in Media Library.

If you want to delete attachment from ML, you should use WP functions. wp_delete_attachment might come in handy.

You can use it like so:

<?php wp_delete_attachment( <ID_OF_YOUR_ATTACHMENT> ); ?>
  • Thanks for answering. It is clear to me now the reason. How do I get this ID? Currently I get the file information using the wp_handle_upload function but in the return values ​​I only have $file, $url and $type. – user615274 Dec 10 '18 at 23:36
  • I just tried developer.wordpress.org/reference/functions/… function but I always get in return 0. I am expecting an ID in this way but no success $id = attachment_url_to_postid($upload['url']); $id is always 0 – user615274 Dec 10 '18 at 23:51

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.