Trigger Ads Based on Post Word Count

Somewhere along the way I found this little function for counting the words in a WordPress post.

function blog_post_wordcount() {

global $page, $pages;
if ( !function_exists(‘str_word_count’) ) {
return str_word_count(strip_tags($pages[$page-1]));
} else {
return count(explode(” “,strip_tags($pages[$page-1])));
}
}

I did not use it until recently when it occured to me how this could help me with my ad displays. I tend to micro blog alot, meaning my posts are very short. I have always liked to place ads in posts and wrap the content around them, however, when you have a very short post this can cause quite an issue with formatting.

I took this function and placed it in my Themes function.php file, I then wrote a little if statement to tell my blog to place ads in posts only when a post contains over 100 words.

<?php
$words=blog_post_wordcount();
if ( $words >= 100 ) {
?>
<div class=”wrapleft”>
*** ADS GO HERE
</div>
<?php } ?>

Of course you could adjust what size ads and how many words to trigger those ads with a couple minor changes.

Leave a Reply

Your email address will not be published. Required fields are marked *