Inserting an html code between paragraphs in a post

February 2013 WordPress Theme
GK User
Tue Sep 24, 2013 11:09 am
I'm looking for a simple solution to add html code between paragraphs in posts. I tried to change file content-single.php:

I replaced
Code: Select all
<?php the_content(); ?>


with this
Code: Select all
<?php
$paragraphAfter= 1; //shows the ad after paragraph 1
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
for ($i = 0; $i <count($content); $i++) {
if ($i == $paragraphAfter) { ?>
<!-- START OF AD CODE -->
PASTE AD CODE HERE
<!-- END OF AD CODE -->
<?php
}
echo $content[$i] . "</p>";
} ?>


Unfortunately this method does not work on your theme. Could you please give me simple solution to make it working?
User avatar
Senior Boarder

GK User
Tue Sep 24, 2013 11:30 am
OK. I found the solution. I changed functions.php file:

Code: Select all
add_filter('the_content', 'mte_add_incontent_ad');
function mte_add_incontent_ad($content)
{   if(is_single()){
      $content_block = explode('<p>',$content);
      if(!empty($content_block[2]))
      {   $content_block[2] .= 'insert_ad_code_here';
      }
      for($i=1;$i<count($content_block);$i++)
      {   $content_block[$i] = '<p>'.$content_block[$i];
      }
      $content = implode('',$content_block);
   }
   return $content;   
}
User avatar
Senior Boarder

GK User
Tue Sep 24, 2013 10:15 pm
With latest WP versions it is better to do "global" filtering with content, with queries.
Thanks for sharing correct solution.
User avatar
Moderator


cron
Remember me
Register New Account
If you are old Gavick user, click HERE for steps to retrieve your account.