Show Ads Based on Content Length

Filed in: Make Money Online, WordPress — February 17th, 2007

advertisement

Problem: Currently I am displaying two blocks of ads on each blog post, one at the top of post, the other at the end of post.

The ad placement is ok but it becomes a problem when I have short posts, which looks like a full page of ads with hidden content. I want to selectively show second ad block only if content is more than 100 words.

By referring to a word count code on WordPress Support, I managed to hide second ad block if content is less than 100 words.

Here is the code. It is for WordPress only. Add the following code after "the_content" function in the "single.php" of your WordPress theme.

PHP:
  1. <?php
  2. $countpost = $post->post_content;
  3. $countpost = preg_replace('/\s+/', ' ', strip_tags($countpost)); // remove white space and html
  4. $words = ((count(explode(" ",$countpost)) + count(explode(".\r",$countpost)))-1); // count spaces and periods
  5. if ($words> 100) {
  6. ?>
  7. <!-- YOUR AD CODE HERE-->
  8. <?php } ?>

My two cents

This is a simple WordPress hack. I hope you find it useful to have more flexible control on ad placements.

Bookmark and Share

Read also:

  • emm.. thanks for the tips ;-)
  • Very informative and practical blogging tricks.

    Happy Chinese New Year LcF!
blog comments powered by Disqus