Friday, 4 December 2009

From my latest Google Analytics figures, 52% of the visitors to this website are from outside the UK. I decided to put Google Adsense on my blog posts as I wanted to show relevant ads and take advantage of it's geo-targeting features, so, for example, a visitor from Germany would see German adverts. I decided the best place for the ads is in the 'related posts' box below each blog article. As related posts are rendered from code behind by a custom control, it's not as simple as just pasting in the Google Adsense code. So, here's the trick to add Adsense, or anything else you want, to the related posts control.

Open up RelatedPosts.cs, which is in App_Data/Controls/, find this line at the end of the CreateList sub procedure;

    sb.Append("</div>");

..and add this before it;

    sb.Append("<br /><br /><script type=\"text/javascript\"><!--");

            sb.AppendLine();

            sb.Append("google_ad_client = \"pub-YOUR AD ID\";");

            sb.AppendLine();

            sb.Append("/* Bottom of blog posts */");

            sb.AppendLine();

            sb.Append("google_ad_slot = \"YOUR AD ID\";");

            sb.AppendLine();

            sb.Append("google_ad_width = 468;");

            sb.AppendLine();

            sb.Append("google_ad_height = 60;");

            sb.AppendLine();

            sb.Append("//-->");

            sb.AppendLine();

            sb.Append("</script>");

            sb.AppendLine();

            sb.Append("<script type=\"text/javascript\" src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\">");

            sb.AppendLine();

            sb.Append("</script>");

            sb.AppendLine(); 


blog comments powered by Disqus