Using WordPress Custom Fields to Control AdSense Sizes

Two of the most common AdSense placements on blogs are

  1. A rectangular ad (such as the 250×250 unit) in the post, floated to the left, with the text wrapping around it.
  2. A 468×60 “banner” unit between the post title and the content.

In some posts, though, the floated ads get in the way of other elements, such as images. Suppose you want to have an image floated to the right, at the top of your post. That could conflict with your ad, couldn’t it? If the image is wide enough, it would run right into the ad. Or what if you wanted to have a wide image above the content, like on Copyblogger? That left-floated ad would get in the way. What’s the solution? No, you don’t need to switch to a 468×60 ad, which often doesn’t perform as well as the floated ad. It’s time for a little WordPress magic.

You’ve probably heard of WordPress’s Custom Fields Feature. On the Write Post page, you can assign any sort of metadata to a post. I recommend reading the WordPress Codex entry about the feature, unless you’re already knowledgeable about the topic.

With a little bit of work, you can use Custom Fields to say “hey WordPress, don’t put the floated ad in this post!” and have the 468×60 ad unit substituted in the post.

First, you need to add a custom field to any post you want to have the banner on instead of the floated ad.

WordPress Custom Fields

I use the key “adtype” for doing this, and the value “wide” to specify the 468×60 ad.

Of course, this doesn’t do anything yet. You need to make some changes to your template first. Use the following code as an example:

<?php $adtype = get_post_meta($post->ID, "adtype", TRUE); if ($adtype == "wide") { ?>
<div style="margin-top:5px;">
[The 468x60 ad code]
</div>
<?php } else { ?>
<div style="float:left; padding-right: 20px;">
[The 200x200 ad code]
</div>
<?php } ?>

This block of code would go between the post title, and the <?php the_content(); ?> template tag. After it’s in place, you just need paste the AdSense code over the placeholders I’ve marked.

I’ve found this solution to be useful, and easy enough to use, in the past, and I believe that a lot of AdSense users will find it useful. Not bad for ten minutes of work, eh?

  • Pingback: Using WordPress Custom Fields to Control AdSense Sizes | Create a Blog

  • http://www.cleverjunction.com/cjr/adsense_insurance John Carnegie

    Thanks for a very informative post.  I will send your blog link to my readers.

  • http://camillesourgetrarebooks.com antiquarian books

    Thank you for this information. :)

  • http://www.freechristianresources.org David

    This is useful, thanks. I've just started testing it on my website and it is working well. It is very flexible, which is just what I needed. I think I may play around with the code and see what extra functionality I can add!