Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:Tomhanna/Adding Ads to Wordpress

This article is a ROUGH DRAFT. The author is still working on this document, so please do not edit this without the author's permission. The content within this article may not yet be verified or valid. This information is subject to change.

Once you have your WordPress site up, it is natural to want to have it "pay you back" and WordPress permits easy inclusion of advertising. Remember, adding advertising code is no different in principle from adding other code, such as Podcasting or Buttons and Icons. You still need to use the basic tools of valid XHTML and valid CSS. Of course, it helps to start with valid code before adding advertising.

Introduction to Website Advertising

Your first step in adding Ads to your WordPress blog should be to familiarize yourself with the available advertising options. You should look at the types of ads and the revenue models to determine which is most compatible with your blog. You will want to examine the pros and cons of the various methods of integrating ads into your blog and understand the issues they may create. After you have determined the types of ads, you'll be ready to work on placing ads in the blog.

Context Sensitive 
Context Sensitive Ads index the individual pages of a website for keywords and then serve ads tailored to those keywords. The ads served with one post are often completely different from ads served with another post because of the keyword indexing. Because of the indexing component, Context Sensitive ads are generally associated with search engines. It may be useful to review the information on Search Engine Optimization for Wordpress. This ad style includes Yahoo Publisher Network and Google Adsense.
Contextual Ads 
Contextual ads are similar to Context Sensitive ads but serve ads based on broad categories, usually chosen at the time of signup, rather than indexing the page for specific keywords. They generally return similar results on all of a site's pages. An example of this type is Adbrite, which serves ads based on your sites category. These are not truly context sensitive as they do not change based on the keywords on a given page.
Brokered Ads 
Brokered ads offer advertisers a way to purchase ads on specific blogs without dealing with each individual blog owner on billing and other issues. The broker offers you script to place on your page inviting readers to advertise on your blog. The broker receives a share of revenue from ad sales. These include BlogAds, which is an invitation only network, and AdBrite. BlogAds offers site visitors the opportunity to purchase ads on your blog and to search their network to purchase ads on multiple blogs. You have the option to approve or reject these ads. AdBrite offers your site's viewers an option to purchase advertising on your site, in addition to serving contextual network ads. You have the option to approve or reject these ads, too.
Affiliate Programs 
Affiliate programs pay you for sales, leads or other actions taken by your site's visitors when they click on the ad. Amazon.com's Associates Program was one of the first affiliate advertising programs on the web. Larger affiliate networks such as Commission Junction and Linkshare combine multiple merchants on one site, making it easy to offer a variety of products while dealing with just one source.
Text Links Ads 
Text Links are growing in importance as a Search Engine Optimization technique. Text links are generally valued based on the site's Page Rank and generally only feasible for Page Ranks above 5. Text link values are also reduced by having too many links on a page, so blogs with long blogrolls probably won't qualify. For more information, see Search Engine Optimization for Wordpress. You can sell text links directly or through brokers such as Textlinkbrokers.com and Text Link Ads.
Tip Jars and Donation Requests 
Tip jars and subscriptions are not really advertising, but do produce revenue for some blogs. Examples of this are the Amazon Honor System and PayPal's Donation System.

Ad Revenue Models

There are different models for "making a sale" and revenue for website advertising. They include:

Pay per click 
Pay you each time a reader clicks on an ad. Usually a few cents per click, though very highly valued keywords can bring $10 or more per click.
Pay per sale 
Pay you when a reader clicks through and makes a purchase. Some of these are flat amounts per sale while others may pay a percent commission.
Pay per lead 
Pay you when a reader clicks through and fills out a form, provides an email address, etc.
Pay per action 
Generic term for any ad that requires the reader to take an action for you to get paid. Includes pay per click, pay per sale and pay per lead.
Pay per impression 
Pay you a certain amount each time the ad is served. May only pay once per unique user.
Pay per day/week/month/etc. 
Pay you a flat fee for the time period agreed, regardless of traffic fluctuations, click through rates, etc.

Ad Integration Methods

Advertisers have several different ways of including ads in websites. For all of these methods, the biggest concerns are style and validation. The ads need to work within your WordPress Theme and changes to the Theme can create validation errors. After adding a new advertising program, your first step should be to revalidate. Your next step should be to check your blog, preferably in multiple browsers to ensure that the HTML in use works within your WordPress Theme.

The different ad integration methods include:

Many ad programs use Javascript to serve the most current ad or to serve contextual ads. If the program's Terms of Service (TOS) allows it, consider placing Javascripts in external files and these other tips for Using Javascript. Javascript based ads require the reader to have Javascript enabled and many adblockers actually look for and block Javascripts.
HTML based advertising involves adding HTML tags and code to your site. This can disrupt your CSS and HTML, so be sure and validate your site after including the HTML ads.
Some advertising programs use Macromedia Flash plugins. Concerns with Flash include load time and, occasionally, validation issues. As with other techniques, revalidate after adding any Flash-based ad.
Text links, which are really just simple HTML ads, are growing in prominence. Again, since these will be incorporated with your Theme, always validate your site after adding them.

How to Place Advertising

Once you have lined up advertisers, you are now ready to begin placing the code in your blog.

General Tips

Start with a clean slate. Solve any other issues your blog may have before you start adding advertising code. Looking through the Support Forums, you may see questions related to a specific ad program. Remember that many of the principles will be the same for any program that uses similar methods (i.e. Javascript) to place the ads on your site.

You can place ads directly in your Template Files or there are Plugins available to help with placing and managing advertising code.

Familiarize yourself with the specific Template Files you intend to modify before you start adding advertisement code.

When editing Template Files to include advertising code either use the Theme Editor in the Administration_Panels or use a plain text editor.

Some HTML and text ads can be aligned horizontally using the text-align CSS property. More complicated issues of alignment and position within the various template files can be solved using proper CSS styling.

Again, always check and validate your site after each change, preferably in multiple browsers. It is much easier to solve one problem at a time than to wait until they accumulate.

Ads in the Header

Some Themes will allow you to place ads (or anything) in the header template file easily. The ads are added to the header.php template file. If your Theme creates the header using a <div> or <span>, you can usually place your ad code inside that and have it appear in the header. In the following example, the ad will appear just under your blog name:

<h1 id="header">
<a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a>

Other Themes, often based on the Default WordPress Theme, create the header by assigning the header class/id to a headline tag that is wrapped around the title. If your Theme does that, you will likely need to place the advertising code below the Header in the content or comparable section.

<div id="header">
 <div id="headerimg">
    <a href="<?php echo get_settings('home'); ?>">
       <?php bloginfo('name'); ?></a>
     <div class="description">
       <?php bloginfo('description'); ?>
<div id="content">

Play around with the placement to get it in the appropriate place dependent upon your header design and layout. Be sure and validate your page afterwards to ensure the placement works.

Ads in The Sidebar

You can add ads to the sidebar by editing the sidebar.php template file. The standard WordPress sidebar template file features a complex nested list, so take care not to disturb the nest. You can carefully integrate ads into the list, or restructure the list to remove the nesting feature if the ad's code interupts the list format. Or add the ads to the top or bottom of the nested list, skipping any possible coding conflicts. To include the code inside of the list, you may need to put your advertisers code between a pair of <li> </li> tags or your page will not validate and may not look right. For example, you may want to include an ad between the Pages and Archives in your sidebar:

<?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?>
    <?php wp_get_archives('type=monthly'); ?>

Inside the Content Template

Multiple and single page views use different template tags to generate the "content" section of a web page in WordPress. All may be generated with the index.php template file, or only multiple post views will use it while single post views will use the single.php template file. If you want ads to appear on these different views, check your WordPress Theme to find out if your Theme uses different template files to display the different web page views.

In general, look for the WordPress Loop as your focal point for placing the ads. It begins with code that looks typically like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

Placing code just after this will generally place the advertising above each post's content. On multi-post views, the ad will be generated at the top of each excerpt or post, such as on the front page. On single post views, the ad will be at the top of the post.

The the_content() is the template tag that returns the post content. Placing advertising code just before or just after this will put your code as close as possible to the "guts" of the post.

<div class="entry">
<?php the_content('Read the rest of this entry »'); ?>

Ads Near Comments

The Comment code at the bottom of the posts produces the link to the Comment page. Place your advertising code just before this to have it appear ahead of the Comment link.

For standard comments, to place your ad just over the comment link look for something like this:

<a href=">?php comments_link(); ?>">Comments to this post</a>

If you use popup comments:

<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?> 

Placing ad code on the Comment Page is an effective way to get an extra ad without violating your program's TOS agreement, limiting the number of ads per page. To add comments to your comment section, on the single post view or popup comments page, comments.php or comments-popup.php such as:

<?php if ('open' == $post->comment_status) : ?>
<h3 id="respond">Leave a Reply</h3>


<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
<p>You must be <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?
redirect_to=<?php the_permalink(); ?>">logged in</a> to post a comment.</p>
<?php else : ?>
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php"
method="post" id="commentform">

This example will place the advertisement just below the "Leave a Reply".

After the First Post

Some advertising programs limit the number of ads per page, so you may need to only include ads after the first (or second or third) post. Here is an example:

  1. Edit index.php of your current theme.
  2. Look for:
    <?php if ($posts) : foreach ($posts as $post) : start_wp(); ?>
  3. This is called The Loop. Its purpose is to display posts. Just BEFORE that line, insert this code:
    <?php $postnum = 1; $showads = 1; ?>
  4. We've just created two variables, $postnum and $showads. The first will be incremented for every new post displayed. The second variable ($showads) is the number of posts you want to display before seeing ads. Next, find this code:
    <?php endforeach; else: ?>
  5. That line is the end of The Loop. Just BEFORE that line, add this:
    <?php if ($postnum == $showads) { ?> <<ADD ADVERTISING HERE>> <?php } $postnum++; ?>
  6. Make the appropriate changes such as inserting the advertiser's code where noted. The $showads variable can be changed from '1' to whatever post you want it to display after.
  7. Save the file.

Here is a simple example. It will show ads after the 5th post of a page.

<?php $postnum = 1; $showads = 5; ?>
<?php if ($posts) : foreach ($posts as $post) : start_wp(); ?>
   <?php the_content(); ?>
   <?php if ($postnum == $showads) { ?> <<ADD ADVERTISING HERE>> <?php } $postnum++; ?>
<?php endforeach; else: ?>
  There are no posts!
<?php endif; ?>

Ads in Feeds

Before placing ads in Feeds, check your advertising program's TOS as some advertisers do not allow this. Two options for placing ads in Feeds are Kanoodle, which produces a substitute feed including contextual ads, and Feedburner, which produces a substitute feed that can include context sensitive ads and automatically insert your Amazon Associates ID into existing links to Amazon products.

Ads in Individual Posts

Placing ads in individual posts can be done by simply including the code in the post in some cases. To include ads powered by PHP will require a plugin to allow the code to be executed. RunPHP and PHPExec let you embed dynamic PHP code and PHP based advertising in individual posts. To use Javascript-based ads in individual posts, see Using Javascript.

Adding Style to Ads

You may want to use some simple CSS to wrap the post around your advertising. In this example, the ad will appear in the upper right of each post, with the post text wrapped around it.

<div style="float:right; margin:2px;"> <<ADD ADVERTISING HERE>> </div>

Of course, you can also create styles for ads in your stylesheet.

Plugins for Advertising

There are a variety of WordPress Plugins that can assist you in adding advertising to your WordPress site. For a general list of all of them, see the Advertising Plugins List.

Cg-PowerPack Includes the CG-Inline plugin and CG-Amazon 
CG-Inline is a powerful macro system for embedding auto-generated items within your posts/articles. In combination with CG-Amazon, allows for quick insertion of Amazon links/images within a post. Flexible image inlines, for floating/embedded thumbnails or image links. Powerful permalink creation. CG-Amazon provides live Amazon data feeds, product links, wishlist links, keyword lookups, all product types/catalogs, article inlined and sidebars, keyword lookups, admin interface and caching system.
Adds content before specified posts (ex: an advertising banner between 1st and 2nd post).
Search and include items from Amazon.com to your post entries. This plugin adds a link called "Insert item from Amazon.com"? on the post page. This link launches a search window which allows an author to search for items from Amazon.com to be included on the author's post entry.
Adsense Beautifier 
Adsense beautifier is a plugin available for Wordpress to make your Adsense look beautiful in order to increase you Adsense earnings. Images adjacent to ads can help increase click through rate (CTR).

Troubleshooting Ads

If you are having trouble with your ads, here are some possible solutions.

Why Aren't My Ads Showing Up?

In many cases it has nothing to do with WordPress, but here are a few things to remember or questions to ask yourself:

  1. With the context sensitive ad services, often the reason is that the keywords for context sensitive ads come from a search engine. Try a search for the URL where the ads should appear in the associated search engine and if the URL is not indexed, you will not get ads.
  2. Many ads use Javascripts. Some of those scripts do not validate correctly and some of them may behave oddly with certain stylesheet features or even with other scripts on the same page.
  3. Doublecheck your placement. For example, if you included the ad code in the Post section of the Main template file and now you are looking at a Page instead of a Post.
  4. Are you running a firewall, ad blocker or other software that may block the ad code? Do you have Javascript enabled in your browser? If the ad uses Flash or another plugin, do you have the required plugin installed?
  5. Try a thorough reload of the page. Clear your browser cache and cookies. Shut down your browser. Restart the browser. Load the page.

All I Get are Ads for Blogs

Context sensitive ads spider your site and index the keywords. If your site is heavy on words and links related to blogging, you will get lots of ads related to blogging. There are two things you can do to improve this. First, eliminate unnecessary blogging references. Second, make longer, keyword rich posts. Posts over 250 words tend to produce better context sensitive ads.

If you are using Google's Adsense and having this problem, you may be able to see some improvement by using section targeting.

I Get Different Ads on Different Pages

If you find you are getting different ads at example.com/index.php than from the URI example.com, this issue with context sensitive ads may be because the search engine reads these as two separate URLs and may index them on different days.

The URL with index.php may be read by the search engine more or less often than the same page without the index.php. Once both are properly indexed, the ads should match -- at least for a while. The only solution, other than time, is to do everything you can to eliminate the use of the index.php in links, etc. A similar situation can occur with www.example.com reading differently than example.com without the www.

My Sidebar is Off the Page

These issues are generally related to XHTML and CSS validation. Check that your site validates as there may be a lost or unclosed tag.

The Ads Confuse Internet Explorer

Internet Explorer is not 100% standards compliant, so even if everything validates, you can still have problems. You may want to look at CSS Fixing Browser Bugs and you may also want to consider using conditional style sheets to direct Internet Explorer to its own stylesheet.