Don't Miss!!

Saturday, 13 May 2017

#Wordpress: How To Automatically Insert Ads After First Paragraph

Hey folks, how are you doing today?...hope you're fine. Thanks for finding this topic as it is of much interest to you. Well you must have come across or seen some blogs with ads in the middle or whichever position in articles of each post, okay if you think of doing the same then hold on a continue reading this article. Putting ads code inside a post it's of a tricky job especially non-coders but still there are much simpler ways of doing even without coding classes you can still go on and do it yourself. i bet with this tutorial you can also call yourself a genius..well i i always do that...lol

Enough with talking, 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 final result of this code is that it will be automatically be inserted by the script into the post after predetermined mark. In this tutorial, ads code will be inserted into each posts after first closing paragraph (html, paragraph), then the ads will appear in every post right after the first paragraph.

Below is a script behind the trick 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.

and that's how you do it, now you can insert ads after first paragraph automatically in wordpress with ease. Go ahead and call yourself a genius'@@@. If there are any questions please comment below, I will be happy to answer your questions.

No comments:

Post a Comment