Using wordpress custom fields to control Ads in your blog

by Veerasundar on October 23, 2008

in How To,PHP

Custom fields are the user defined information that are assigned to any blog post in WordPress. They are also called as meta-data. Blog authors usually define the custom fields when they write the blog post to give some extra information like mood, whether,etc. Custom fields are key/value pairs, that means you can define any key and assign any value to this key. To know more about custom fields check out WordPress.org site. With this explanation, it is easy to control the ad presence in your blog post easily with custom fields.

Control ad presence in blog post with custom fields

As a blog author, you may want to include ad in some of your blog posts and may not want to have ads in other blogs. But it will be tedious to make a code change every time you post a blog. So we are going to define a custom field $show_ad and in the blog template we will check for this custom field. And, if it is YES we will include the advertisement and if it is NO or NULL we are not going to insert the advertisement.

Code changes to check for a custom field

  1. Open the single.php wordpress template file
  2. Search for the text the_content and after this line, insert the below code. This will put the advertisement in the bottom of every post. If you want to place your ad on top of every post, copy below code above to the the_content line.
  3. Code to be inserted
    <?php
    	$show_ad=get_post_meta($post->ID, 'show_ad',TRUE);
    	if (strtoupper($show_ad) == "YES")
    	{
    		echo 'YOUR AD CODE IS HERE';
    	}
    ?>
    
  4. Save the changes.
  5. After this, when ever you want to insert ad in your blog post, just define a custom field show_ad and give it a value “YES”. Your ad code will be inserted to this post alone. If you don’t want to insert ad, just don’t define any custom fields. So simple, isn’t it?

{ 7 comments… read them below or add one }

Venkat December 27, 2008 at 1:59 AM

Hi,

I was just looking for this type of ad insertion in selected posts. Great! Thank you very much for this information.

Reply

Veerasundar December 27, 2008 at 3:14 AM

You are welcome, Venkat!

Reply

Alexwebmaster March 3, 2009 at 8:08 AM

Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru

Reply

Rebecca March 19, 2009 at 3:22 PM

Very helpful but how would you get the click through stats? Thank you in advance for your help – much appreciated

Reply

Veerasundar March 19, 2009 at 5:03 PM

Hi Rebecca,

I think getting the click through rates (CTR) for the Google adsense ads, is impossible, because Google will never expose these details to outside world, through any APIs.

Reply

mark June 28, 2009 at 4:36 PM

Hi.Very nice website.I will come back again.

Reply

paul oconnor June 28, 2009 at 5:11 PM

great website and informations.thanx

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: