I'm storing an uploaded attachment to a custom directory under wp-content/uploads/my-directory/ and storing its value in wp_postmeta table. When I'm deleting the post it's not deleting the attached file from the path.

So I tried hooking onto the delete_post hook to delete the file from its path:

 * Delete Custom Attachment when deleting its post.
 * @param integer $post_id Post ID.
 * @return void
function wpse353942_delete_attachment( $post_id ) {
    if ( 'my-cpt' !== get_post_type( $post_id ) ) {

    $attachment = get_post_meta( $post_id, '_attachment', true ); // get the attachment URL.
    if ( ! $attachment ) {

    $upload_dir = wp_get_upload_dir();
    unlink( $upload_dir['basedir'] . '/my-directory/' . basename( $attachment ) );

add_action( 'delete_post', 'wpse353942_delete_attachment' );

But alas, it's not deleting the file from the directory. :(

What can I do?


If you see the code of wp_delete_post() function, you can see that, the function is deleting the post's meta data just before deleting the post itself - a line above with the delete_metadata_by_mid().

So, in your function, when you are trying to get the attachment URL, it's already been deleted from the database, so it's getting empty and the function is returning doing nothing.

So the best approach would be to hook on to a prior one instead of delete_post - you can use: the before_delete_post hook with the same function, and it should work.

Just change:

add_action( 'delete_post', 'wpse353942_delete_attachment' );


add_action( 'before_delete_post', 'wpse353942_delete_attachment' );


  1. Action Hook: delete_post - Developer Reference
  2. Function: wp_delete_post() - Developer Reference
  3. Function: delete_metadata_by_mid() - Developer Reference
  4. Action Hook: before_delete_post - Developer Reference
| improve this answer | |

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.