How to Insert Ads within your Post Content in WordPress

By | June 7, 2014
0
0



Have you seen blogs that has ads inside their post content? These ads are either after the first paragraph or the second paragraph in most cases. Most beginners wonder whether these sites insert ads manually when they write the content, or if there is a special code for this. In this article, we will show you how to insert ads within your post content after specific paragraphs.

Often when beginners want to include ads in their post, they either add the code manually which is extremely inefficient specially if you have to change advertisers, or they insert ads above or below their post using one of the ad management plugins.

Well, we’ve been adding ads in List25 after first paragraphs, and a lot of users asked about it, so here’s the easiest way to do it.

Simply install and activate the plugin we created called Insert Post Ads. Upon activation, the plugin will add a new menu item called Post Adverts.

Click on Post Adverts » Add New. On the next screen, simply add the name of your ad for identification purposes, enter the ad code itself, and select the paragraph you want to display the ad code after. Once done simply click publish.

Insert Post Ads

Next you want to go to Post Adverts » Settings to select which post types you want to show your ads on such as posts, pages, and custom post types.

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

Open your theme’s functions.php or a site-specific plugin file and paste the following code:

<?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 );
}

To add your ad code, simply edit $ad_code value where it says “Ad code goes here” on line 9. Once you do that, you are done. To change the paragraph number, simply change the number 2 to another paragraph number on line 12.

We hope that this article helped you insert ads within your post content in WordPress.

Leave a Reply

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