Insert Google Ads Inside Post Content - WordPress Snippet

Insert Google Ads Inside Post Content – WordPress Snippet

There are many plugins that can help you achieve this, but if you prefer to do it yourself here is the code snippet for you. Insert this into you functions.php

 

<?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[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column row_column_index="0_1" type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][$index] .= $closing_p;
		}

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

	return implode( '', $paragraphs );
}

How to insert Insert Google Ads Inside Post Content – Solved !!

If you liked this article share it on your favorite social network below.[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]

Nikola Petrovic
Get in Touch

Nikola Petrovic

Hi there. My name is Nikola,
I speak English, Greek and Serbian.
As a Web Producer i can deal with almost anything web design & development related.
As a freelancer, I charge only a small portion of the money you would pay to agencies to create your website. Affordable web design doesn’t mean that it will lack any of the advanced features of today’s web technology. We just cut out the cost of the middle man.
Feel free to request a free quote using the form on the right or the one bellow.
Nikola Petrovic
Get in Touch