Skip to content

Instantly share code, notes, and snippets.

@tingplenting
Last active May 22, 2016 07:10
Show Gist options
  • Save tingplenting/6f8310c826cdb8ba774af8c8be6dc77a to your computer and use it in GitHub Desktop.
Save tingplenting/6f8310c826cdb8ba774af8c8be6dc77a to your computer and use it in GitHub Desktop.
<?php
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div id="googleads-1"></div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
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