In our last post we looked at hard coding your Google Adsense code to the loop in your index page. That will display Adsense on your home page and your archive pages. In this post we’ll look at creating a short code to place adsense in your posts on the fly without having to copy and paste your Adsense code. This requires us to add a function and a short code to the functions.php page of your theme.
Don’t worry, it’s not complicated at all. Just open your functions.php file in your theme’s folder and scroll to the bottom of the file. Here we’ll add the following code:
function adsense( $code ) {
$code = '
Your adsense code
';
return $code;
}
add_shortcode( 'myAds', 'adsense' );
Just insert you adsense code in place of the line: Your adsense code, save the file and upload it to your server. Now, when you’re writing a post, you can just type the [myAds] short code where ever you want your Adsense to appear.
A word of warning though, you might want to put the short code after the read more quick tag (<!--more-->) or it will show up in the loop and you might end up have more than the permitted number of ads on a page! Alternatively, you can use the is_single() conditional tag in the function to ensure that the Adsense code is only inserted when the single post is viewed, and not when it’s in the loop.
Just replace the code above with the following code:
function adsense( $code ) {
if ( ! is_single() ) {
$code = ' ';
} else {
$code = '
Your adsense code
';
}
return $code;
}
add_shortcode( 'myAds', 'adsense' );

Leave a reply