3

I have a function wp_handle_upload() for uploads files.

$file = $_FILES['attachment_icon-' . $i];
$upload = wp_handle_upload($file, array('test_form' => false));

what is a function for delete a uploaded file?

2 Answers 2

7

Use wp_delete_attachment( $post_id ) if you have used wp_insert_attachment() before.
$post_id is the attachment ID.

If you haven’t used wp_insert_attachment() a simple …

unlink( $upload['file'] );

… will do it.

2
  • wp_delete_attachment does not remove the file if it was not added via wp_handle_upload. It was added using wp_insert_attachment, but it was uploaded beforehand via file_put_contents (file received in base64). Should I just use unlink then? But then relations in DB will stay for old files?
    – trainoasis
    Nov 16, 2015 at 8:38
  • In my case I verify that the file is actually removed from the file system but a reference to the file remains in the media library list. Please read this question about it wordpress.stackexchange.com/questions/321595/…
    – user615274
    Dec 10, 2018 at 23:27
3

there is no designated WP function, simply because you already have a PHP one, with the following syntax:

    <?php
    $filename="MyFile.txt"
    unlink($filename);
    ?>

for full doc see the PHP manual:

http://php.net/manual/en/function.unlink.php

1
  • This would leave dead entries in the database if it is already registered.
    – fuxia
    Jan 8, 2012 at 21:33

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.