Automatic Table of contents with categories and posts

Here is a plugin that does the same.

function get_posts_per_taxterm($taxonomy, $term_id ){
    $posts = get_posts(
        array(
            'posts_per_page' => -1,
            'post_type' => 'post',
            'orderby'  => 'menu_order',
            'order'    => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => $taxonomy,
                    'field' => 'term_id',
                    'terms' => $term_id,
                    'include_children' => false
                )
            )
        )
    );
    // `first_post_id` is a global variable which contains the ID of the post which comes first inside TOC
    // @toDo Find a better way
    global $first_post_id;
    if(!isset($first_post_id)){
        if (!empty($posts)){
            $first_post_id = $posts[0]->ID;
        }
    }
    return $posts;
}
function get_array_of_posts_grouped_by_taxterms($terms, $parent_id = 0, $outputs = []) {
    foreach ($terms as $term) {
        if ($parent_id == $term->parent) {
            $outputs['<a data-id = "'.$term->term_id.'" class = "elementor-kb-term-href stm-content" href="https://wordpress.stackexchange.com/questions/294817/.get_term_link($term->term_id).">'.$term->name.'</a>'] = get_array_of_posts_grouped_by_taxterms( $terms, $term->term_id);
            $posts= get_posts_per_taxterm('category',$term->term_id);
            foreach ($posts as $post){
                $outputs['<a data-id = "'.$term->term_id.'" class = "elementor-kb-term-href stm-content" href="https://wordpress.stackexchange.com/questions/294817/.get_term_link($term->term_id).">'.$term->name.'</a>'][] = '<a class = "elementor-kb-post-href stm-content" href=".get_permalink($post->ID)." data-id="'.$post->ID.'">'.$post->post_title.'</a>';
            }
        }
    }
    return $outputs;
}