I want to insert an ad code in the middle of a post via functions.php.

I found several links but either they don't use functions.php or don't insert the code in the middle.

Can anyone tell me how to do this?

Also, I don't want to use a plugin.

  • 4
    No research efforts, no reason for no plugin, not even your own code … please invest more time into your question.
    – fuxia
    Jul 22, 2012 at 12:11

2 Answers 2


This function inserts your ad code after the specified paragraph.

add_filter('the_content', 'wpse_ad_content');

function wpse_ad_content($content)
    if (!is_single()) return $content;
    $paragraphAfter = 2; //Enter number of paragraphs to display ad after.
    $content = explode("</p>", $content);
    $new_content = '';
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $paragraphAfter) {
            $new_content.= '<div style="width: 300px; height: 250px; padding: 6px 6px 6px 0; float: left; margin-left: 0; margin-right: 18px;">';
            $new_content.= '//Enter your ad code here....';
            $new_content.= '</div>';

        $new_content.= $content[$i] . "</p>";

    return $new_content;
  • 3
    @Programmer : & I want a Ferrari this christmas..! . . . . . . . $paragraphAfter = count(it)/2 !!
    – brasofilo
    Jul 16, 2012 at 12:08
  • If there is only one paragraph, the ad will not be displayed.
    – Knott
    Oct 10, 2014 at 6:28
  • This worked very well. I used it to insert a shortcode for a slider that appears after X paragraphs.
    – Alexnl
    Apr 8, 2020 at 18:54

There are several alternatives:

First, you can use shortcodes as @iambriansreed suggest, but you need to know PHP programming to register the shortcode. The following code is from a website (in spanish) that shows how to program a simple shortcode with Adsense:

 * Copy the code into your theme's functions.php file
 * Change the AdSense <script> for yours 
function showads() {
    return '<div><script type="text/javascript"><!--
    google_ad_client = "pub-XXXXXXXXXXXXXX";
    google_ad_slot = "4668915978";
    google_ad_width = 468;
    google_ad_height = 60;

<script type="text/javascript"

add_shortcode('adsense', 'showads');

Second, you can use a plugin like Quick Adsense to achieve the same shortcode but easily customizable or let the plugin select where to put the ads.

And finally, you can write your own code to add ads at n-th paragraph (i.e. exploiting each paragraph and selecting the n-th paragraph and add there your ads code). It's not the best solution but it will be fully customizable.

Not the answer you're looking for? Browse other questions tagged or ask your own question.