How to split a post and intercalate elements from a loop

What I’m trying to achieve is spreading related posts throughout the content – such as one reccomendation after every 3 paragraphs.

As I see it, three things need be done:

1 – Do the loop. What I’m using now is something like this:

$related = new WP_Query( array( ‘post__in’ => $whatever) );
if ( $related->have_posts() ) { while ( $related->have_posts() ) { $related->the_post(); get_template_part(‘relatedpost’); }}
wp_reset_query();

2 – Split the post – I’m using this code, that works great for static content such as ads.

function insert_related_post( $text ) {
if ( is_single() ) :
$insert = ‘’;
$split_by = “</p>”;
$insert_after = 3; //number of paragraphs
// make array of paragraphs
$paragraphs = explode( $split_by, $text);
$new_text = ”; // new text
$i = 1; // current ad index
// loop through array and build string for output
foreach( $paragraphs as $paragraph ) {
// add paragraph, preceeded by an ad after every $insert_after
$new_text .= ( $i % $insert_after == 0 ? $insert : ” ) . $paragraph;
// increase index
$i++;
}
return $new_text;
endif;
echo $text;
}
add_filter(‘the_content’, ‘insert_related_post’);

3 – Insert each element in the loop after every third paragraph. That, I can’t figure how to do.

I suppose that the iterations should look something like this…

$related = new WP_Query( array( ‘post__in’ => $whatever, ‘posts_per_page’ => ‘1’, ‘offset’ => $i++/3) );
if ( $related->have_posts() ) { while ( $related->have_posts() ) { $related->the_post(); get_template_part(‘relatedpost’); }}
wp_reset_query();

…but I can’t manage to have that work – so where/how could I put it?

Read more here:: How to split a post and intercalate elements from a loop

Leave a Reply

Your email address will not be published. Required fields are marked *