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?


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.

  • 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 '15 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 '18 at 23:27

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


for full doc see the PHP manual:


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

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.