You can use these two snippets to insert something after X paragraphs in your WordPress post. You need both snippets.
There are plugins to take care of this, but sometimes it’s more desirable to have something a little more permanent built into a WordPress theme.
Or in some cases you might want to insert a shortcode or php function in the middle of your content. Great use cases for this are table of contents plugins or video ads, to name a few.
There is the parent function, which takes care of the functionality. Then there is the individual insert function. This way you can also use a second or third insertion function, and all functions make use of the functionality of the parent function.
You don’t necessarily need to know how the functions work exactly. All you need to know is that:
- $ad_code is a variable that represents what it is you want to insert. This can be a string of text or a snippet of HTML. In this case make sure to paste it within the parentheses. It can also be a shortcode. In that case put the shortcode inside the do_shortcode() function, and comment out the first variable.
- The number or integer (here 1) is the number of paragraphs after which you want to insert the content.
As always, put the functions into your child theme’s functions.php. It does not matter in which order you put both functions. Don’t forget to change prefix_ with something specific to your site.
Individual Insert Function:
// Individual Insert Function
// Insert ads after x paragraph of single post content.
function prefix_insert_post_part( $content ) {
if ( is_singular('post') && ! is_admin() ) {
$ad_code = "The thing you're inserting here";
// $ad_code = do_shortcode('');
return prefix_insert_after_paragraph( $ad_code, 1, $content ); // integer is # paragraphs to skip
}
return $content;
}
add_filter( 'the_content', 'prefix_insert_post_part' );
Parent Function:
// Parent Function
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 );
}