How to add ads Code after 400 Chars


How to insert ads after 400 charsIf below the Post title is one of the most successful position for Google Adsense ads, Then between the text is another most successful
position for Google Adsense ads.

There are a lots of plugins are out there to perform this particular task but as we all know extra plugin means extra loading time. This is the main
reason, I love to implement all these types of hacks in my own theme.

The below code will ad a new adsense unit of any post that is more than 1000 char logn and this adsene code will be after 400 chars
in such posts, other post having less then 1000 chars will be there as it is i.e. there will be no adsense unit in such posts

To implement Adsense code after 400 chars, just open your functions.php file and add the following code in it. The below script will ad
this adsense unit after first break.

<?php
function inject_ad_text_after_n_chars($content) {
// only do this if post is longer than 1000 characters
$enable_length = 1000;
// insert after the first </p> after 400 characters
$after_character = 400;
if (is_single() && strlen($content) > $enable_length) {
$before_content = substr($content, 0, $after_character);
$after_content = substr($content, $after_character);
$after_content = explode('</p>', $after_content);
$text = '
<br />
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90, created 6/19/10 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-2922826112079493"
     data-ad-slot="3928010150"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
';
array_splice($after_content, 1, 0, $text);
$after_content = implode('</p>', $after_content);
return $before_content . $after_content;
}
else {
return $content;
}
}
add_filter('the_content', 'inject_ad_text_after_n_chars');
?>

Point to Remember  :

Do not forget to replace my adsene code with your adsene code and also remove opening php tag and closing php tag at the end.
of this function.




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>