Skip to content

Instantly share code, notes, and snippets.

@carlitoescobar
Created February 25, 2018 20:42
Show Gist options
  • Save carlitoescobar/de09f38c931847c88072f65464ac5cc6 to your computer and use it in GitHub Desktop.
Save carlitoescobar/de09f38c931847c88072f65464ac5cc6 to your computer and use it in GitHub Desktop.
<?php
/**
* Adding an ad after the second paragraph
*
*/
add_filter( 'the_content', 'tb_insert_post_ads' );
function tb_insert_post_ads( $content ) {
$ad_code = 'The ad code goes here. Both static ads and Google Adsense.';
if ( is_single() && ! is_admin() ) {
// The number in front of the content defines where the code appears. Here, it pops up after the article's second paragraph.
return tb_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function tb_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