Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active February 23, 2019 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/84350abfe4b833a4e072 to your computer and use it in GitHub Desktop.
Save billerickson/84350abfe4b833a4e072 to your computer and use it in GitHub Desktop.
<?php
/**
* Insert after Paragraph
* When running on the_content, use priority > 20 so it doesn't affect oEmbed
*
* @param string $insertion
* @param int $paragraph_id
* @param string $content
* @return string $modified_content
*/
function ea_insert_after_paragraph( $insertion, $paragraph_id, $content, $include_at_end = true ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, wpautop( $content ) );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
$inserted = true;
}
}
if( ! $inserted && $include_at_end )
$paragraphs[] = $insertion;
return implode( '', $paragraphs );
}
@JiveDig
Copy link

JiveDig commented Aug 23, 2016

Hey Bill. Where does $inserted come from, on line 26?

@billerickson
Copy link
Author

@JiveDig sorry about that, just now saw this.

I added $inserted on line 23. The idea is if the paragraph ID you specify is greater than the number of paragraphs total, then add the insertion at the end of the content.

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