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 '12 at 12:11

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 '12 at 12:08
  • If there is only one paragraph, the ad will not be displayed. – Knott Oct 10 '14 at 6:28

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.

protected by Community Oct 12 '15 at 6:33

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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