Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hirejordansmith/36a220666e64f827067f1f19b4734b49 to your computer and use it in GitHub Desktop.
Save hirejordansmith/36a220666e64f827067f1f19b4734b49 to your computer and use it in GitHub Desktop.
Insert Content in WordPress after a certain amount of paragraphs
<?php
//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 );
}
@bruno-barros
Copy link

Nice code. I found an edge case when there is a table and inside a cell there are paragraphs. Each paragraph inside the table count. So the result is totally unexpected. Maybe an regex is need here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment