title: Add custom content in the middle of Wordpress post
body: <p>How would I go about changing this code so that it inserts the custom content after half of the paragraphs in a given post? If a post has 12 paragraphs, the content should be inserted after number 6. If it has 100, it should be inserted after number 50.</p>
  
  <p>I have found this code online, where you can specify a hard coded number of paragraphs:</p>
  
  <pre><code>&lt;?php
  //Insert ads after second paragraph of single post content.
  add_filter( 'the_content', 'prefix_insert_post_ads' );
  function prefix_insert_post_ads( $content ) {
   $ad_code = '&lt;div&gt;Ads code goes here&lt;/div&gt;';
   if ( is_single() &amp;&amp; ! is_admin() ) {
   return prefix_insert_after_paragraph( $ad_code, 2, $content );
   }
  return $content;
  }
  
  // Parent Function that makes the magic happen
  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>
  
  <p>I do not know enough PHP to make it dynamic. I have not found a dynamic answer to this elsewhere.</p>