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.
2 Answers
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;
}