Placing an ad or content block on single post after certain paragraph – WordPress Tip

If you ever have to show an ad or content block on a single post page – under a certain paragraph (eg. right after the first paragraph) – you can use the code below by replacing the_content.

<?php
$ad_placement_p = 2;
$content = apply_filters('the_content', $post->post_content);if(substr_count($content, '<p>') > $ad_placement_p)
{
	$contents = explode("</p>", $content);
	$p_count = 1;
	foreach($contents as $content)
	{
		echo $content;
 
		if($p_count == $ad_placement_p)
		{
		?>
               Your Ad Code
		<?php
		}
		echo "</p>";
		$p_count++;
	}
}
?>

The way it works is by using < p > as marker of position. Feel free to change $ad_placement_p value to assign locations of this content/ad block.

Leave a Reply

Your email address will not be published. Required fields are marked *