Insert Ad Code in the Middle of a Post

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.

Read More

Can anyone tell me how to do this?

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

Related posts

Leave a Reply

2 comments

  1. 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;
    }
    
  2. 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>
    
    <script type="text/javascript"
    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script></div>';
    }
    
    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.