If you index $related_posts
by position along with $ad_posts
, you can probably splice/insert them in at the same position… eg.
function wpse_210493_apply_advertising_position(&$posts, $return = false)
{
$ad_posts = array();
$content_posts = array();
$related_post = array();
// Seperate $posts into "Ads" and "Content" arrays based on whether or not they have 'rw_adversiting_position' meta-data
foreach ($posts as $post) {
$position = get_post_meta($post->ID, 'rw_adversiting_position', true);
$post_date = $post->post_date;
$post_modified = $post->post_modified;
// add an index to related_posts inside the position check
if (!empty($position)) {
// move this inside position check
$related_post = get_post_meta($post->ID, 'rw_advertising_related_link', true);
if (isset($ad_posts[$position])) {
if ($post_date > $ad_posts[$position]->post_date || $post_modified > $ad_posts[$position]->post_modified) {
$ad_posts[$position] = $post;
// add position index to related post
if ($related_post) {$related_post[$position] = $related_post;}
}
} else {
$ad_posts[$position] = $post;
// add position index to related post
if ($related_post) {$related_post[$position] = $related_post;}
}
} else {
$content_posts[] = $post;
}
}
// Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads
ksort($ad_posts);
// Add the ads back into the content at their specified positions
foreach ($ad_posts as $position => $ad) {
array_splice($content_posts, $position, 0, array($ad));
// add the match related post in
array_splice($content_posts, $position, 0, array($related_post[$position]));
}
// then there is no need for this now
// foreach ($content_posts as $key => $post) {
// if (in_array($post->ID, $related_post)) {
// unset($content_posts[$key]);
// }
// }
return $content_posts;
}