Hi there, in this article we are going to show you how to extend WordPress functionality, how to delete post attachments associated to each of your WordPress post.
How to correctly delete post attachments upon post/page deletion?, there are times when the client wants 
to delete post attachments and other medias pertaining to a specific post 
or any other custom post types that you registered to WordPress upon the deletion of that post.


By default WordPress doesn't delete post attachments automatically ,deleting a post does not cascade
to the attachments of that post, because of that you can end up with a lots of unused attachments
in your library that will only take up hard drive space.

But it's good to know that WordPress provides a lot of action hooks and filters that allows developer
to insert and extends custom functionality, so to get this done we are going to hook at 
WordPress action hook before_delete_postbefore_delete_post - fired before post metadata are deleted.. Codex it!

So if your ready lets get our hands dirty. To correctly delete post attachments associated with upon post/page deletion. Open up your current theme functions.php file be sure to have a backup copy of the file. Copy and paste the code below.
Please be advised that : Attachments are deleted only from the library if post are completely deleted on trash.Another key to be noted that media must be uploaded to the post.How to do so? See screenshot provided below.
/**
 * Delete post attachment together with post/product are deleted,
 * In this code I have specified post types of type "product".
 * You can specify custom post type, that you want to deal with.
 */
function delete_associated_media($id) {
 //check if product
 if ('product' !== get_post_type($id)) return;

 $media = get_children(array(
 'post_parent' => $id,
 'post_type' => 'attachment'
 ));

 //if no media associated with
 if(empty($media)) return;

 foreach ($media as $file) {
 //pick what you want to do
 wp_delete_attachment($file->ID);
 }
}

//used action hook "before_delete_post"
add_action('before_delete_post', 'delete_associated_media');

Please see this screenshot to know how to upload attachment to make it associated to a post.

image