Here’s what I’ve used after finding something on the web (wpbeginner).
It finds the fourth p tag closing and adds it after that. Originally it was to add ad banners in the middle of post content dynamically.
add_filter( 'the_content', 'prefix_insert_post_related' );
function prefix_insert_post_related( $content ) {
$related_code .= do_shortcode("[divider]");
$related_code .= do_shortcode("[bws_related_posts]");
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $related_code, 4, $content );
}
return $content;
}
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 );
}