Google Adsense Shortcode

Tutorials | By Paul Maloney | 25 November 2010 | Comments 11

A friend asked me today was there an easy way to add Google adsense ads within WordPress without actually filling the template files full of the implementation code, the answer was yes.. use shortcodes!

So here is how you can add your Google adsense blocks to your blog without pasting lines and lines of code, the following snippets take place within the functions.php file, so remember to backup first.

Add to functions.php

function google_adsense() {
return '<div>
<script type="text/javascript">
<!--
google_ad_client = "PUB-ID";
google_ad_slot = "AD-SLOT";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>';
}
add_shortcode('adsense', 'google_adsense');

You will need to add your PUB ID, the ad Slot Number and the ad sizes (width and height), I also put it inside a class so you can style using CSS within your theme stylesheet like this:

.adsense {margin: 5px; padding: 5px;}

Now when you need to place an adsense block you can do so like this:

[adsense]

If you have a couple of different ad sizes you can reuse the snippet but rename the function and class then add different heights and widths like so:

function google_adsense2() {
return '<div>
<script type="text/javascript">
<!--
google_ad_client = "PUB-ID";
google_ad_slot = "AD-SLOT";
google_ad_width = 125;
google_ad_height = 125;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>';
}
add_shortcode('adsense2', 'google_adsense2');

and to call it in your pages and posts:

[adsense2]

Pretty easy huh?

Paul Maloney

Paul Maloney is a UK based web designer/developer and runs the design agency Tropica. He particularly enjoys using and working with WordPress and has a keen interest in typography. You can also follow Paul on Twitter.

Visit Paul Maloney's website

11 Comments

  • November 25, 2010
  • November 25, 2010
  • November 25, 2010
  • November 26, 2010
  • November 26, 2010
  • November 26, 2010
  • November 26, 2010
  • December 5, 2010
  • February 15, 2011

Leave A Comment.