Home» »How to insert ads after first paragraph automatically

How to insert ads after first paragraph automatically

You must have seen a blog with adsense in the middle articles of each post, if you think to put adsense code every time you make a post, then you are wrong, because there are other easier ways to insert ads after first paragraph automatically.

There is an easier way to insert ads after first paragraph automatically in wordpress  using a script that is put in the functions.php file. This method is much easier and more effective, because you do not need to touch the script adsense again during making articles.


The workings of this method is the ads code will inserted by the script into the post after a predetermined mark. In this tutorial, ads code will be inserted into each posts after first closing p (html, paragraph), then the ads will appear in every post right after the first paragraph.

Well, here is the script that must be inserted into your functions.php file to insert ads after first paragraph automatically in wordpress.

//Insert ads after first paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
     function prefix_insert_post_ads( $content ) {
 
 $ad_code = '<div>Ads code goes here</div>';

 if ( is_single() && ! is_admin() ) {
  return prefix_insert_after_paragraph( $ad_code, 1, $content );
 }
 
 return $content;
}

// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
 $closing_p = '</p>';
 $paragraphs = explode( $closing_p, $content );
 foreach ($paragraphs as $index => $paragraph) {

  if ( trim( $paragraph ) ) {
   $paragraphs[$index] .= $closing_p;
  }

  if ( $paragraph_id == $index + 1 ) {
   $paragraphs[$index] .= $insertion;
  }
 }
 
 return implode( '', $paragraphs );
}

Once you put the above code into functions, things you should do next is replace the red part with your ads code. You can also change the number of paragraphs by changing the orange part. Suppose I change the number of paragraph to 2, then the ad will appear after the second paragraph.

That's it, now you can insert ads after first paragraph automatically in wordpress with ease. If there are any questions please comment below, I will be happy to answer your questions.

About Author:

Rahman Kurnia is a blogger, SEO fighter, who loves PHP, CSS, HTML and interested in js, ajax, c++ and much more. He love writing something informatif to help others, and to keep his knowledge on the internet.

Follow him @ Twitter | Facebook | Google +

2 comments:

  1. Untuk blogspot ada kodenya ngga?
    Nyari brbulan bulan gk dapet

    ReplyDelete
  2. Untuk blogspot ada kodenya ngga?
    Nyari brbulan bulan gk dapet

    ReplyDelete

Like us on Facebook
Follow us on Twitter
Recommend us on Google Plus
Blog Widget by LinkWithin