How To Wrap Google Adsense In WordPress Posts Correctly

written by aext on January 21, 2010 in WordPress with 57 comments

It’s easy to add Google Adsense code in the top, the bottom of WordPress posts by edit your WordPress theme posts file. However, sometime you need to wrap Google Adsense code in WordPress posts, and you can not do as the same way as add it on top, bottom. This article will explain you how to do that.

For coupe of months ago, I published a post WordPress Hack: Anything Can Be Added Anywhere In The Post Content. With that tutorial, you can add anything in WordPress posts on top, bottom before other plugins do, even right below the post excerpt.

Updated: Thanks to Jonathan Foucher and Nathan J. Brauer for notify me the replacement function. I need to visit more often on php manual site.

1. Replacement using str_replace() function

The only one way for you to insert Google Adsense or anything in WordPress Posts is using str_replace() function to scan the whole content for the string like <!-googlead-> then replace it by the Google Adsense code.

First, create a function like this one below in functions.php file:

function googleadsense($content){

  $adsensecode = 'GOOGLE ADSENSE GOES HERE';

  $pattern = '<!-googlead->';

  $content = str_replace($pattern, $adsensecode, $content);

  return $content;      
}

add_filter('the_content', 'googleadsense');

That’s all you need. Now, whenever you publish a post, insert <!-googlead-> in post content where you want Google Adsense to be displayed.

[smartads]

2. Using Shortcode API

From version 2.5.1, WordPress has supported Shortcode API, a simple set of functions for creating macro codes for use in post content. We need to write a function which is a shortcode handler function in funtions.php file. The return value of a shortcode handler function is inserted into the post content output in place of the shortcode macro.

In this case, we will use the shortcode [googlead] to insert Google Adsense code in WordPress post. All the code we need is:

function googlead_shortcode() {

  $adsensecode = 'GOOGLE ADSENSE SHORCODE GOES HERE';

  return $adsensecode;
}

add_shortcode('googlead', 'googlead_shortcode');

Refer to the code above, when the_content is displayed, the shortcode API will parse any registered shortcodes such as [googlead]. The return (Google Adsense code) by the shortcode handler will be inserted into the post body in place of the shortcode [googlead] itself.

In my conclusion, these two code snippets above is the simplest and easiest to insert wrap Google Adsense code in WordPress posts. However, you sometime need to change the Google Adsense code to display, you should use the WordPress Option value for Google Adsense code instead of adding the ad code in functions.php file. Have you tried to add options for your WordPress theme before? If not, please take a look at this post: WordPress Theme Design with Options Adminstration. Hope this post is useful for you!