Skip to content

Instantly share code, notes, and snippets.

@oakwoodgates
Last active August 29, 2015 14:16
Show Gist options
  • Save oakwoodgates/429f741390a154eb44f0 to your computer and use it in GitHub Desktop.
Save oakwoodgates/429f741390a154eb44f0 to your computer and use it in GitHub Desktop.
add_filter( 'the_content', 'prefix_insert_post_ads' );
/**
* Insert code for ads after second paragraph of single post content.
*
* @param string $content Post content
*
* @return string Amended content
*/
function prefix_insert_post_ads( $content ) {
$content_callout = '<h4>Insert code for ads after second paragraph of single post content.</h4>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $content_callout, 2, $content );
}
return $content;
}
/**
* Insert something after a specific paragraph in some content.
*
* @param string $insertion Likely HTML markup, ad script code etc.
* @param int $paragraph_id After which paragraph should the insertion be added. Starts at 1.
* @param string $content Likely HTML markup.
*
* @return string Likely HTML markup.
*/
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
// Only add closing tag to non-empty paragraphs
if ( trim( $paragraph ) ) {
// Adding closing markup now, rather than at implode, means insertion
// is outside of the paragraph markup, and not just inside of it.
$paragraphs[$index] .= $closing_p;
}
// + 1 allows for considering the first paragraph as #1, not #0.
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