title: Adding addcode at the center based on number of paragraphs
body: <p>I have my website setup to display an add on the 7th paragraph. Because not every post is as long as the other this can cause some weird ad placements.</p>
  
  <p>Instead I would like to use the following logic: </p>
  
  <p><code>If number_of_paragraphs =&gt; 14</code> then <code>paragraph_insert_id= number_of_paragraphs / 2</code>. <code>Else nothing</code>.</p>
  
  <pre><code>//adding mid post add based on paragraph
  add_filter( 'the_content', 'prefix_insert_post_ads_mid' );
  
  function prefix_insert_post_ads_mid( $content ) {
  
      $ad_code = '&lt;div id="adsensemid"&gt;code goes here&lt;/div&gt;';
  
      if ( is_single() &amp;&amp; ! is_admin() ) {
          return prefix_insert_after_paragraph( $ad_code, $content );
      }
  
      return $content;
  }
  
  
  function prefix_insert_after_paragraph( $insertion, $content ) {
      $closing_p = '&lt;/p&gt;';
      $paragraphs = explode( $closing_p, $content );
      // floor or ceil; to make it round
      $mid = ceil(length($paragraphs) / 2);
      foreach ($paragraphs as $index =&gt; $paragraph) {
  
          if ( trim( $paragraph ) ) {
              $paragraphs[$index] .= $closing_p;
          }
  
          if ( $mid == $index + 1 ) {
              $paragraphs[$index] .= $insertion;
          }
      }
  
      return implode( '', $paragraphs );
  }
  </code></pre>
  
  <p>Unfortunately my first modifications already broke the script. When applied to the website all content is blank. Is there someone that can find the flaw? Any help would be hugely appreciated!</p>
  
  <p>ps current working script:</p>
  
  <pre><code>//adding mid post add based on paragraph
  add_filter( 'the_content', 'prefix_insert_post_ads_mid' );
  
  function prefix_insert_post_ads_mid( $content ) {
  
      $ad_code = '&lt;div id="adsensemid&gt;&lt;/div&gt;';
  
      if ( is_single() &amp;&amp; ! is_admin() ) {
          return prefix_insert_after_paragraph( $ad_code, 7, $content );
      }
  
      return $content;
  }
  
  
  function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
      $closing_p = '&lt;/p&gt;';
      $paragraphs = explode( $closing_p, $content );
      foreach ($paragraphs as $index =&gt; $paragraph) {
  
          if ( trim( $paragraph ) ) {
              $paragraphs[$index] .= $closing_p;
          }
  
          if ( $paragraph_id == $index + 1 ) {
              $paragraphs[$index] .= $insertion;
          }
      }
  
      return implode( '', $paragraphs );
  }
  </code></pre>