Add Google Adsense Code to WordPress Post,Page without Plugin

Ways to Add Google Adsense Code to WordPress Post,Page without Plugin

Now in case you don’t like using the WordPress plugin, and want to do it the code way, then follow below  directions

  1. Login to your WordPress admin panel say www.xyz/wp-admin/
  2. Go to Appearance section and click theme editor
  3. Open your theme’s functions.php and paste the below  code inside this  <?php                             ?>:

Suppose you want to insert ads only inside posts but not pages  in wordpress then paste the below  code in your theme’s functions.php inside this  

<?php                             ?> :

//Insert ads after second 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, 2, $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 );
}

Suppose you want to insert ads between Post,Page,attachment in wordpress then paste the below code in your theme’s functions.php

inside this  <?php                             ?>;



//Insert ads after second paragraph of Post,Page 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_singular() && ! is_admin() ) {
 return prefix_insert_after_paragraph( $ad_code, 2, $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 );
}


Note-

where it says “Ad code goes here” simply paste your adsense code 


where it says
is_single(), which only places ads in single posts, so if you want ads
in post,page,attachment then you should use is_singular(), which test for is_single(), is_page() or is_attachment()

Urgent APPEAL-Help Save our WebSite

Donate any amount