Putting ads on your WordPress site is quite a personal choice: for some it will be one of the first things you do, while others will resist it for a while. This seemed like a simple idea, but there was more to it. The standard call for displaying your WordPress content (the_content) is just a single line that automatically pulls the entire post from the database from beginning to end, so inserting something in the middle of it is not as easy as it sounds.
However, you can use the following code in place of your content call to enable you to place your ad code (or any other type of code) after a set number of paragraphs. So, open up your theme editor and open single.php for editing and look for the following line:
< ?php the_content(); ? >
Now you’ll want to replace that with the following code snippet. Don’t worry about it’s apparent complexity – there’s only two simple variables in there that you will need to change:
< ?php
$show_after_p = 2;
$content = apply_filters('the_content', $post->post_content);
if(substr_count($content, '
') > $show_after_p)
{
$contents = explode("
", $content);
$p_count = 1;
foreach($contents as $content)
{
echo $content;
if($p_count == $show_after_p)
{
?>
YOUR AD CODE GOES HERE OR WIDGET SIDEBAR CODE
< ?php
}
echo "
";
$p_count++;
}
}
? >
In this example, the ad will be displayed after the second paragraph. This is as a result of the $show_after_p = 2 line near the top of the snippet. You can change this to another value to suit your needs.
The other thing you will need to change is the ad code itself. Two thirds of the way down, you will see a spot that says YOUR AD CODE GOES HERE. This is where you should place your AdSense or other code.