When an attachment is permanently deleted, the file will also be removed. Deletion removes all post meta fields, taxonomy, comments, etc. associated with the attachment (except the main post).
The attachment is moved to the Trash instead of permanently deleted unless Trash for media is disabled, item is already in the Trash, or $force_delete is true.
We will irrevocably delete the attachment with ID 54:
wp_delete_attachment( 54, true );
0
#2 Delete all post attachments (attached files), along with the deletion of the post
On some blogs it is convenient to make it so that when you delete a post, all the media files attached to it would be deleted along with it. You can do it this way:
// Deletes all post attachments (attached media files) along with the post(s)
add_action( 'before_delete_post', 'wpkama_delete_attaches_with_post' );
function wpkama_delete_attaches_with_post( $post_id ) {
$post = get_post( $post_id );
$post_types = [ 'article', 'question' ]; // delete attachments only for these post types
if( ! $post || ! in_array( $post->post_type, $post_types ) ){
return;
}
$attaches = get_children( [
'post_type' => 'attachment',
'post_parent' => $post_id,
] );
if( ! $attaches ){
return;
}
foreach( $attaches as $attach ){
wp_delete_attachment( $attach->ID, true );
}
}
The hook before_delete_post, because when the post is deleted, all attachments take the status unattached, i.e. the post_parent value is deleted, and the post attachments are selected by it. So the hooks delete_post and after_delete_post will not work.