
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?
Thanks a lot for this tip. I really like it very much.
Wicked shorthand mate, thanks for sharing
@a_usman no problem!
@john cheers mate
Awesome shortcode! I’m going to try this out right now
this is too good
That’s the shortest way to do the ad placement. Btw, the same things can be achieve using wordpress filters too!
Hey buddy, simple but a great tip… might be very useful if you want to use adds on the middle of the posts!
Great tip and a good solution to adding code to pages/posts but would the shortcodes not be lost if functions.php is replaced during a WP upgrade? Does the code need to be added to functions.php or is there any way of doing it in say a shortcodes.php file that would never be overwritten?
This great, i will try this, so simple
Pages
Categories
Archives
Blogroll
Twitter
Popular Posts
Twitter Followers
Recent Posts
Recent Comments