The code below tries to remove any post found on $related_post
but my approach is not working since $content_post
is returned with those ones. I tried to fix but is not working and I can't see where I am messing up things. Take a look at the following code:
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 = intval(get_post_meta($post->ID, 'rw_adversiting_position', true));
$post_date = $post->post_date;
$post_modified = $post->post_modified;
// each post with meta rw_adversiting_position
// will have a rw_advertising_related_link
// let's add those to $related_post array
if (intval(get_post_meta($post->ID, 'rw_advertising_related_link', true)) != 0) {
$related_post[] = intval(get_post_meta($post->ID, 'rw_advertising_related_link', true));
}
if (!empty($position)) {
if (isset($ad_posts[$position])) {
if ($post_date > $ad_posts[$position]->post_date || $post_modified > $ad_posts[$position]->post_modified) {
$ad_posts[$position] = $post;
}
} else {
$ad_posts[$position] = $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));
}
echo '<pre>';
var_export($related_post);
echo '</pre>';
// if $post is on $related_post let's remove from $content_post
foreach ($content_posts as $post) {
if (in_array($post->ID, $related_post)) {
echo 'YES ' . $post->ID . EOL;
unset($post);
}
}
return $content_posts;
}
This is the output when I run the code:
// var_export($related_post)
array (
0 => 183002,
1 => 182987,
2 => 182923,
3 => 182926,
4 => 182704,
)
// echo 'YES ' . $post->ID . EOL;
YES 183002
YES 182926
So there is at least two elements on the array, why them aren't deleted? what I am doing wrong? What's wrong in my code?
答案 0 :(得分:1)
Can you try to remove from Array key.
// if $post is on $related_post let's remove from $content_post
foreach ($content_posts as $array_key=> $post) {
if (in_array($post->ID, $related_post)) {
echo 'YES ' . $post->ID . EOL;
unset($content_posts[$array_key]);
// unset($post);
}
}