If Your Post Doesn't Start With An Image, Display an Ad Instead

Posted on in Programming

WordPress Horizontal LogoI usually start my posts off with an image that is relevant to the post. I think it adds a bit of drama to what I'm writing about, and it also gives me a nice place to anchor a link to a WordPress tag about the subject. I had this idea the other day that if I didn't include an image at the beginning of a post, I should put a Google AdSense ad there instead.

<!--more-->

The last thing you really want to do in this case is include the Google AdSense code directly in your post content. Instead, it would be great to programmatically check in your theme for an image at the beginning of the post content and then display an ad when necessary. Putting the AdSense code in your content just guarantees that you have to go diving through posts whenever you want to make a tweak.

I didn't end up doing this, but here's one way you can test for an image at the beginning of your content. This snippet in your template's single.php file right before you display the content with the_content().

<?php
    $content = get_the_content();
    if ( substr($content, 0, 4) != "<img" ) {
        # AdSense code here
    }
?>

This method isn't bulletproof. It requires your posts that have images near the top to start with the img tag. If you use something else, or include your images a little farther down, it will break.

Just an idea.

My Bookshelf

Reading Now

Other Stuff