Adding code to the top of every post in WordPress

Again, to monetize my blog, I wanted to add Google AdSense to the top of every post. It turns out, that wasn’t too hard:

  1. Create a php file in the mu-plugins folder
  2. Add the following code to the file

function the_content_googleads($content = '') {
if (is_single()) {
$content = stripslashes(get_googleads_code()) . $content;
else {
$content = stripslashes(get_googleads_code()) . $content;
return $content;
function get_googleads_code()
return '<script type="text/javascript"><!--
google_ad_client = "pub-7920273364077311";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as";
google_ad_type = "text_image";
google_ad_channel = "";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_text = "000000";
google_color_url = "008000";
<script type="text/javascript"
add_filter('the_content', 'the_content_googleads');

Notice the is_single() check which lets you emit different code for when the post is displayed on its own or in a list e.g. on the homepage. In this case, I just emit the same code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s