title: How to get all content with an <h2> tag in WordPress?
body: <p>Sample Content:</p>
  
  <pre><code>&lt;h2 id="h2-1"&gt;H2 Heading (1)&lt;/h2&gt;
  &lt;p&gt;Lorem ipsum dolor sit amet consectetur ...&lt;/p&gt;
  &lt;h3 id="h3-1"&gt;H3 Heading&lt;/h3&gt;
  &lt;h2 id="h2-2"&gt;H2  Heading (2)&lt;/h2&gt;
  </code></pre>
  
  <p>What I'm trying to achieve:</p>
  
  <pre><code>&lt;ul&gt;
    &lt;li&gt;&lt;a href='#h2-1'&gt;H2 Heading (1)&lt;/a&gt;&lt;/
    &lt;li&gt;&lt;a href='#h2-2'&gt;H2 Heading (2)&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>I knew it can be done with a regex function but I don't know how to finish the function. Here's what I have done so far:</p>
  
  <pre><code>function table_of_contents() {
      $content = get_post_field( 'post_content', $post-&gt;ID );
      $tags = preg_match_all( '#&lt;h2&gt;(.*?)&lt;/h2&gt;#', $content, $matches );
  
      return $tags;
  }
  </code></pre>