Disclosure: Some of the links in this post could be "affiliate links." This means if you click on an affiliate link and purchase an item, I will receive an affiliate commission.

Adding Adsense within the Post Content - WordPress & Genesis

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

<?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[$i] . "</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  WPBeginner.com & WPSmith.net 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.

Comments

  1. i love this, using genesis simple hooks to add adsense inside post is awesome, i have been using several plugins to ad adsense to my blogs, but with the genesis simple hooks, i can even edit my footer, thanks a lot for this wonderful help.

  2. Its very nice Tutorial I found.. Thanks!!

  3. coeurmechante says:

    Hi-- this is great for an ad, or an individual element. Once I use it to draw a div, though, it breaks (just displays the div beneath the post, as usual). Any idea why that might be happening, or how to fix? I'm trying to insert a Related Posts div within my post content...

  4. Lee says:

    Hi, will this work for all wordpress themes? Currently I use Thesis and Woo. Cheers

Leave a Reply