Adding Adsense within the Post Content – WordPress & Genesis

Posted on

You might have come across websites that has an ad in the middle of a post, this is a simple guide on how you can achieve this with Genesis.

Insert Ads after x Paragraphs

Save this code to your theme’s root folder, as adsense-inpost.php

    $paragraphAfter= 5; // Insert Ad after 5 paragraphs
    $ad = '<p id="adsense-inpost"> Adsense code goes here </p>';
    $content = apply_filters('the_content', get_the_content());
    $content = explode("</p>", $content);
    for ($i = 0; $i <count($content); $i++ ) {
		if ($i == $paragraphAfter)
			echo $ad;

		echo $content&#91;$i&#93; . "</p>";

Open your functions.php and add this:

add_action('genesis_post_content', 'include_adsense_inpost', 1);
function include_adsense_inpost() {
    if ( is_single() ) {
		remove_action('genesis_post_content', 'genesis_do_post_content');
        require_once(CHILD_DIR . '/adsense-inpost.php');

Big thanks to & for providing most of the code.

Let me know what you think of the code, and if you would do it in some other way.

Founder of