Delete all attachment when delete post or page

Add code to file functions.php in your themes

// Delete all attachment when delete post or page
add_action( 'before_delete_post', 'nlap_delete_all_attached_media' );
function nlap_delete_all_attached_media( $post_id ) {
    if ( get_post_type($post_id) == 'post' || get_post_type($post_id) == 'page' ) {
        $attachments = get_attached_media( '', $post_id );

        foreach ($attachments as $attachment) {
            wp_delete_attachment( $attachment->ID, 'true' );
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *