WordPress - 如何将多个 WP Query 对象合并为一个?

3
在WordPress中,可以为循环创建自己的WP查询。以下是一个示例:
$my_query = new WP_Query(array('post_parent' => 3, 'post_type' => 'page'));

另一个例子是这个:
$my_query = new WP_Query(array('cat' => 1, 'post_type' => 'post'));

我希望有一个循环可以同时展示页面和文章。
现在我有一个问题,这两个对象是否能够合并成一个?如果可以,怎么做?我不想创建两个不同的循环。
2个回答

3
如果您不想使用SQL,这是我制作搜索页面的方法。
基本问题:在进行meta_query时,WordPress认为我希望条件与“AND”而不是“OR”连接。
因此,WordPress会查找标题/内容=“myContent”和aioseop_keyword =“myContent”的页面。这(在我的情况下)导致零结果,尽管有匹配SEO关键字的页面。
为了解决这个问题,我进行了两个查询。听起来很简单,但是:尽管$post对象中有帖子,但循环不想识别帖子。我在查看the have_posts() function后找到了这个解决方案:它引用除$post对象之外的其他变量。
$term = get_search_query(); // same as $_GET['s']

# the normal search:
$wordpress_keyword_search =& new WP_Query(array(
  's'         => $term,
  'showposts' => -1
));

# now push already found post IDs to an array, so we can exclude them from the meta search.
foreach ($wordpress_keyword_search->posts as $post_)
  $exclusion[] = $post_->ID;


# now do the meta query search
$aioseop_keyword_search =& new WP_Query(array(
  'post__not_in' => $exclusion,
  'post_type' => 'any',
  'showposts' => -1,
  'meta_query' => array(            
    array(
      'key'       => '_aioseop_keywords',
      'value'     => $term,
      'compare'   => 'LIKE',
    )
  )
));

# merge the two array posts.
# post_count and found_posts must be added together also. 
# otherwise have_posts() returns false.
# see: http://core.trac.wordpress.org/browser/tags/3.6.1/wp-includes/query.php#L2886

$wordpress_keyword_search->posts       = array_merge($wordpress_keyword_search->posts, $aioseop_keyword_search->posts );
$wordpress_keyword_search->found_posts = $wordpress_keyword_search->found_posts + $aioseop_keyword_search->found_posts;
$wordpress_keyword_search->post_count  = $wordpress_keyword_search->post_count + $aioseop_keyword_search->post_count;

然后在一个简单的循环中使用它:
if ($wordpress_keyword_search->have_posts()) {
  while($wordpress_keyword_search->have_posts()) {
    $wordpress_keyword_search->the_post();
    # now you simply can:
    the_title();
    the_content();

  }
} else {
  echo '<p>Sorry, no posts found</p>';
}

2
您想要的将被翻译为SQL中的WHERE ... OR ...条件或UNION,例如:
SELECT * FROM posts WHERE (post_parent = 3 AND post_type = 'page') 
  OR (cat = 1 AND post_type = 'post')

或者

SELECT * FROM posts WHERE post_parent = 3 AND post_type = 'page'
  UNION
SELECT * FROM posts WHERE cat = 1 AND post_type = 'post'

从查看源代码和WP_Query()构造SQL的方式来看,我认为这是不可能的:查询变量既没有OR也没有UNION。
我能想到的唯一方法是编写一个插件,实现posts_where过滤器(应用于返回文章数组的WHERE子句)。您可以使用不同的WP Query调用此插件,并且该插件将获取它们的WHERE部分并将它们OR在一起。
另请参见http://codex.wordpress.org/Custom_Queries

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接