Insert Ad Code in the Middle of a Post

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;
}

Leave a Comment