Someone have a sample snippet to delete media ID on deleting post?
i have upload metafield that contain array ID of media file attached to post and i wish to delete media files also on deleting post and avoid to have pending/useless media loaded.
thanks
You would be using the delete_post hook, which fires right before a post gets deleted (so you still have access to it). Inside your function, which then fires, you'd fetch all attachments (or attachment IDs) and remove them using wp_delete_attachment.
add_action( 'delete_post', 'delete_attachments_with_posts', 10, 2 );
function delete_attachments_with_posts( $post_id, $post ) {
if ( $post->post_type == 'post' ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
) );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
}
}
References: Hook Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With