How can we insert Google Adsense Ads or some similar content in mind of a WordPress post article? In Adsense, it is better to have the ad in the middle of the article for better revenue. There are two ways of inserting content into the post.
1. Dynamically we can parse the post content and use an existing HTML tag to insert content. For example, we can parse the content and extract/split it based on paragraph HTML tags. Then iterate the tags and insert the Ad or content after a certain number of paragraphs and then display the content in the browser.
2. Manually insert the Ad or content on any place in the post as of our choice. This is like opening the article in the editor and go the place where we want to insert the ad and put the code for ad display there. This step can be done in a modular way.
I prefer way 2 as it gives flexibility to position the ad. Every article is not same and they are not written equally. Some will have smaller paragraphs or lesser number of paragraphs. If we insert ad manually, we have absolute control over the position. Inserting manually is tedious compared to automated parsing but it is worth doing as it is direct $.
Though we insert manually we can use WordPress’s feature which allows us to insert content using a template mechanism and it is better to use it as we can change the content in one place.
Add the above code in functions.php and then add [ads] in the required place in the WordPress post. WordPress engine will dynamically replace the [ads] template tag with the content returned from the function.
This WordPress code tutorial was published on May 19, 2013.