将多个 WP_Query 结果合并到一个不重复的数组中

问题描述 投票:0回答:1

我有一个带有自己的自定义模板的自定义帖子类型,并且我想显示与自定义帖子类型标题相关的博客帖子。但是,我想先显示引用的帖子,然后搜索带有标签的任何帖子,然后再查找相关帖子。其中任何一项都可能导致没有结果或产生很多结果。我要显示的帖子总数是 6。

`

$searchtag = strtolower(get_the_title());

$arg1 = array(
    'post_type'   => 'post',
    'p' => $post_id,
);
$arg2 = array(
    'post_type'   => 'post',
    'tag' => $searchtag,
    'post_status' => 'publish',
    'orderby' => 'post_date',
    'order' => 'desc',
    'posts_per_page' => 6,
);
$arg3 = array(
    'post_type'   => 'post',
    's' => $searchtag,
    'post_status' => 'publish',
    'orderby' => 'relevance',
    'posts_per_page' => 6,
);

// Get the posts
$query1 = new wp_query( $arg1 );
$query2 = new wp_query( $arg2 );
$query3 = new wp_query( $arg3 );
$related_query = new wp_query(); 

// Merge the unique posts
$related_query->posts = array_merge($query1->posts, $query2->posts, $query3->posts);
$related_query->post_count = $query1->post_count + $query2->post_count + $query3->post_count;

if($related_query->have_posts): 

`

我读过一篇文章,指出使用 post__not_in 会对数据库造成负担,我不应该合并它。

  1. 如果query->post_count = 0,我需要添加逻辑吗?
  2. 如何维持订单但确保不显示重复项?

我目前在这些结果中得到重复的结果。我想消除它们,同时保持帖子的顺序,先查询 1,然后查询 2,然后查询 3...显示前 6 篇帖子。

php wordpress array-merge
1个回答
1
投票

更好的方法是使用参数进行 3 次查询:

'fields' => 'ids'

还有:

$postIds1 = get_posts($args1);

合并获取数据时:

$postIds = array_merge(array(0), $postIds1, $postIds2, $postIds3);

当提出请求时

'post__in' => $postIds
© www.soinside.com 2019 - 2024. All rights reserved.