How to add AdSense to WordPress - functions.php

Following up on the first post, here’s an alternative way to add AdSense to WordPress without plugins.

This approach means creating a function that returns the ad code wherever you need it.

Advantages of this method:

  • you can drop the ad into posts using a shortcode
  • you can call the function from code, say from content.php or index.php

Same as in the first post, drop the adsbygoogle.js loading function into footer.php

If you already have it there, no point duplicating it.

Next, from the admin Appearance menu pick Editor and find functions.php
Screenshot from 2014-11-14 15:39:23

At the very end add the following function (copy the code from your adsense account):

function google_ads() {
return '<center><div id="adsenseads"><ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-<strong>xxxxxxxxxxxxxxxx</strong>"
     data-ad-slot="<strong>xxxxxxxxxx</strong>;"></ins>
     <script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div></center>';
}
add_shortcode('gads', 'google_ads');

Calling the function from text

Now using [gads][/gads] in a post’s text will show the AdSense banner

To make life easier - add a button to the editor

Calling the function from code

To show ad blocks on the home page right after the first post’s title, add the following into the <?php while ( have_posts() ) : the_post(); ?> loop in index.php. Note that you need to edit the file inside your theme’s folder (/wp-content/themes/theme-name). To not miss it, use the WordPress admin editor:

<?php if ((($count == 0) && ($_SERVER["REQUEST_URI"] == "/")):?>
    <div style="padding:10px;" align="center"><?php google_ads(); ?></div>
<?php endif; $count++; ?>

Other functions get set up the same way. Might also be useful: A few useful tricks for the WordPress theme functions file