隐藏合并的Wordpress循环中的重复帖子

时间:2016-02-17 15:03:13

标签: php wordpress

我通过合并两个现有的查询创建了一个Wordpress查询,如何阻止第二个查询显示第一个查询已经显示的帖子?

$args_for_query1 = array(
    'meta_key' => '_mcf_homeoperator',
    'meta_value' => 'Yes',
    'posts_per_page' => 14,
    'cat' => 521,
    'post__in'       => get_field('srtby_homepage', 'option', false, false),
    'orderby'        =>  'post__in'
);

$args_for_query2 = array(
    'posts_per_page' => 20,
    'cat' => 12,22411,
    'post__in'       => get_field('srtby_slotspage', 'option', false, false),
    'orderby'        =>  'post__in',
);

$query1 = new WP_Query($args_for_query1);
$query2 = new WP_Query($args_for_query2);

// Main Loop
$args=array(
    'paged' => $paged,
    'showposts' => 20,
);

$wp_query = new WP_Query($args);
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
$wp_query->post_count = $query1->post_count + $query2->post_count;


if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();

1 个答案:

答案 0 :(得分:0)

首先,您无缘无故地运行第三个查询($query),因为您无论如何都要覆盖其中的帖子。

if ($query1->have_posts())
{
    if ($query2->have_posts())
    {
        foreach ($query1->posts as $post)
        {
            foreach ($query2->posts as $key => $post_)
            {
                if ($post->ID == $post_->ID)
                {
                    unset($query2->posts[$key]);
                    break;
                }
            }
        }
        if (count($query2->posts) > 0)
        {
            $query1->posts=array_merge($query1->posts, $query2->posts);
            $query1->post_count=count($query1->posts);
        }
    }
}
else
{
    //whatever you do if there are no posts
}