How to Manually Add AdSense in a WordPress Post

You can manually add AdSense in a WordPress post above or below the content without any issue. You can simply place the necessary code above, or below, the the_content(); function call. Now if you want to place it within the content, it is a bit more complex.

Most people would install a plugin that will automatically insert your AdSense code into the content of any post. I have used them in the past, but found that it would break the post readability if the code was inserted into the wrong location. Also, some people wish to reduce the number of plugins that are activated in the blog, so a manual method may be better. Once the code is added manually, you can easily monitor your AdSense coverage.

Manually Add AdSense in a WordPress Post Without a Plugin

Google AdSense Logo

In order to place AdSense in your post without a plugin, you would need to edit the single.php file in your theme. You will then replace the the_content(); function call with the code below.

Code to Manually Add AdSense in a WordPress Post

<?php
$show_after_p = 1;
$content = apply_filters('the_content', $post->post_content);
if(substr_count($content, '<p>') > $show_after_p)
{
  $contents = explode("</p>", $content);
  $p_count = 1;
  foreach($contents as $content)
  {
    echo $content;

    if($p_count == $show_after_p)
    {
    ?>
    <!-- Insert code here -->
    <?php
    }
    echo "</p>";
    $p_count++;
  }
}
?>

I should note, however, that the code isn’t mine because I found it online (if someone knows the source, please let me know so I can give proper credit). Basically, you would insert your AdSense code by replacing this line:

<!-- Insert code here -->

After doing that, you can then choose to display the AdSense ads after a specific paragraph by indicating a paragraph number in the following line:

$show_after_p = 1;

While this code only allows you to add AdSense after one paragraph, if you know PHP, then you can modify the code to allow multiple AdSense code insertions.

The above code allows you to manually add AdSense in a WordPress post content so you don’t need to use an additional plugin.

Follow Me