Tag Archives: Google Ad

Adding Google Ad or HTML in the middle of your posts

A quick safe way to automatically add your Google ad or any HTML just in the middle of your wordpress posts;

Simply add the following code to your theme’s function.php file then replace “HTML CODE” with your google ad code, that is it.


/* Content Google Ads */
add_filter( 'the_content', 'wpse_ad_content' );
function wpse_ad_content( $content ) {
if( !is_single() ) return $content;
$paragraphAfter = 3;
$content = explode ( "
", $content );
$new_content = '';
for ( $i = 0; $i < count ( $content ); $i ++ ) {
if ( $i == $paragraphAfter ) { $new_content .= 'HTML CONTENT'; }
$new_content .= $content[$i] . "";
}
return $new_content;
}

With this, your Google Ad or any other HTML will appear just after the specified number of paragraphs in your content. Notice the following;

  1. $paragraphAfter = 3;will display the ad after third paragraph.
  2. $new_content .= $content[$i] . ""; You can use this to insert a second HTML or Google Ad after paragraph 6 in the above case where first ad is after paragraph 3.
  3. If you are using a custom theme, be sure to locate the active functions.php file that the theme author set active otherwise the default is located just in the theme directory.

Enjoy