How to Embed Google AdSense Code inside a WordPress Post without Any Plugin

WordPress does not let you embed PHP code inside the posts but uses a feature to create Shortcode functions which are executed whenever they are encountered within a post. This is pretty handy feature since this gives you capability to add some PHP code in your WordPress files and then call it from your posts. The PHP code can be added to Theme’s functions.php file. We can use this to load ads from within the posts.

Go to WordPress administration -> Appearance -> Editor -> By default style.css is opened for editing.

Open functions.php by clicking on the file name on right hand side listing.

Embed Adsense Code in WordPress Posts

Now copy the following code at the end of the file and change the return string to your Adsense code. Shortcode is defined by calling add_shortcode function and passing two parameters to it. The first one is a given name which will be used in the posts to call this function and second parameter is the name of the function.

You can define multiple functions one for each type of ad and then define a Shortcode for each of them and then call them selectively in your post.

// Adsense code enclosed between single quotes when your Adsense code uses double quotes. 
// If it is using single quotes, then enclose it within double quotes.
function getAdSenseCode300x250(){
return '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:300px;height:250px"
     data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
     data-ad-slot="1111111111"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
}

add_shortcode('ad300x250', 'getAdSenseCode300x250');

Click on “Update File” to save this. Now we are all set. In order to embed this ad into a post we need to use name of the Shortcode within square brackets and put it anywhere in the post.

For ex  [ads300x250] can be added anywhere in the post which will display ad at that location. I have changed the name from the example otherwise it would have simply loaded the ad.

See the ad below which is being loaded using this method.

Another tip; if you want to align this to center in stead of left, simply select the Shortcode and center align it using the rich text editor control. No special code is required to align the ad per your liking.

 


Leave A Comment

Your email address will not be published.