Skip to content

Instantly share code, notes, and snippets.

@SteveJonesDev
Created May 9, 2018 18:41
Show Gist options
  • Save SteveJonesDev/c4dc8f7dc39cc1ff2bacda99980948a3 to your computer and use it in GitHub Desktop.
Save SteveJonesDev/c4dc8f7dc39cc1ff2bacda99980948a3 to your computer and use it in GitHub Desktop.
How to insert custom code into the WordPress post content
<?php // dont include this line
//Insert code after second paragraph of single post content.
add_filter( 'the_content', 'sj_insert_code' );
function sj_insert_code( $content ) {
$code = '<div>Code to be inserted goes here</div>';
if ( is_single() && ! is_admin() ) {
return sj_insert_after_paragraph( $code, 2, $content );
}
return $content;
}
//Parent Function that makes the magic happen
function sj_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