I’ve worked with wordpress for many years. Sometimes, i have to delete post for some reasons and i see that wordpress doesn’t delete attachments (such as photos and files). This will cause wasting our server/hosting resource for unecessary thing.

Automatically delete post attachments after delete a wordpress post
This php function will automatically delete all post attachments right after we delete a wordpress post.
function delete_all_attached_media( $post_id ) { if ( get_post_type($post_id) == "post" ) { $attachments = get_attached_media( '', $post_id ); foreach ($attachments as $attachment) { wp_delete_attachment( $attachment->ID, 'true' ); } } } add_action( 'before_delete_post', 'delete_all_attached_media' );
How to use:
Copy and paste the code to functions.php which is located in your current theme directory. Then try to delete a wordpress post which has some attachments, you will see it works so perfectly.
Customize with other wordpress custom post type
The code is so easy to understand. As you can see the line: get_post_type($post_id) == “post”. Just change post to a custom post type that you want the function work.