Adsense WordPress Shortcode

Adsense WordPress Shortcode: In the following simple solution, I will show you how to create a WordPress Shortcode that can be used to display your Google Adsense ads anywhere within your posts or pages. This simple function added to your Themes functions.php file, makes it very easy to include your Adsense Ads with  post or page content while you are writing the content for your blog.

Adding Adsense WordPress Shortcode

  1. Login to your WordPress site and navigate to Appearance > Editor.
  2. Select Theme Functions (functions.php) from the Theme Files on the right.
  3. On a blank line just before the closing ?> tag add the following, replacing the javascript code in red with your actual Adsense Code:

    function adsense_shortcode( $atts ) {
    extract(shortcode_atts(array(
    'format' => '1',
    ), $atts));

    switch ($format) {
    case 1 :
    $ad = '<script type="text/javascript"><!--
    google_ad_client = "pub-0000000000";
    /* 336x280 Some Ad */
    google_ad_slot = "80000000";
    google_ad_width = 336;
    google_ad_height = 280;
    //-->
    </script>
    <script type="text/javascript"
    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script>
    ';
    break;
    }
    return $ad;
    }
    add_shortcode('adsense', 'adsense_shortcode');

  4. Click the Update File button to save your changes.
  5. Now when you go to edit or write a new post or page, simply add the [adsense] shortcode and the Adsense ad will be displayed with your post or page content.