WordPress is such a great tool for bloggers and publishers. I`m not making any differentiation between digital writers and others because WordPress, being a CMS, can handle any type of website. But as much as they love to offer free content to the masses, they still have to monetize WordPress in someway and what`s the most convenient way if not Google Adsense?
Integrating Google Adsense into your WordPress theme and displaying it on posts can be done by editing the single.php file. Although this solution works just fine, you`re still limited to the ads you display. But what if you want to add Google ads anywhere in a post? And not only that, what if you want to have some ads in a certain post and other ads in other posts? The solution is to make use of WordPress shortcodes.
I want to show you how you can integrate Google Adsense Ads into any post using shortcodes. For this, we have to create a shortcode for Google Adsense.
All custom functions we built for WordPress have to be added inside
functions.php file. If you don`t have one, create one and paste the next code in it(make sure to use the beginning and ending php tags):
Now, you can use the shortcode
[adsense] in any post or page you want and the ad specific to the google_ad_slot you provided will be rendered. But this is not a very flexible shortcode, right? Let`s make a step forward and extend this shortcode. We`re going to make it render not only an ad, but any type of Google Adsense ad. We`re going to extend “google_ad_slot”, “google_ad_width” and “google_ad_height”. Also, we can wrap the ad block into a div so we can stylize it or center it on the page.
Notice the 3 parameters we give:
height. If you insert a shortcode as
[adsense] into a post, an ad of 250x250px and with the slot id=”0000000000″ will be rendered.
To display a new shortcode with other dimensions and google_ad_slot, use the extended shortcode call:
[adsense slot="1234567890" width="336" height="280"]
This is how you can easily integrate Google Adsense ad blocks inside any place of your WordPress theme, without the need of editing theme files every time you want to change something. Shortcodes are truly amazing and without a doubt you can make the most out of WordPress using them!