How to delete a custom file from upload directory when deleting its post

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' );

into

add_action( 'before_delete_post', 'wpse353942_delete_attachment' );

Reference:

  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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)