Skip to content

Instantly share code, notes, and snippets.

@jeweltheme
Forked from theukedge/gist:6745757
Last active March 21, 2017 12:24
Show Gist options
  • Save jeweltheme/80b49a107891a08a6920258fc68f15ac to your computer and use it in GitHub Desktop.
Save jeweltheme/80b49a107891a08a6920258fc68f15ac to your computer and use it in GitHub Desktop.
<?php
// Example 1
$show_after_p = 2;
$content = apply_filters('the_content', $post->post_content);
if(substr_count($content, '<p>') > $show_after_p)
{
$contents = explode("</p>", $content);
$p_count = 1;
foreach($contents as $content)
{
echo $content;
if($p_count == $show_after_p)
{
?>
YOUR AD CODE GOES HERE
<?php
}
echo "</p>";
$p_count++;
}
}
//Example 2
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment