Wordpress - 将多个 WP Query 对象合并为一个?

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

在 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'));

我想要一个循环,显示来自同一循环的页面和帖子。

现在回答我的问题。是否有可能将这两个对象合二为一?如果是的话,怎么样?我对创建两个不同的循环不感兴趣。

php wordpress object
2个回答
3
投票

如果您不想使用 SQL 来完成此操作,这就是我的搜索页面的方式。

基本问题:在进行meta_query时,wordpress认为我希望条件用“AND”而不是“OR”连接。

因此,Wordpress 会查找标题/内容=“myContent”且 aioseop_keyword“myContent”的页面。尽管有一个页面具有匹配的 SEO 关键字,但这(就我而言)导致结果为零。

为了解决这个问题,我提出了两个问题。听起来很简单,但是:尽管 $post 对象中有帖子,但循环不想识别这些帖子。我在查看了 have_posts() 函数后找到了这个解决方案:它引用了其他变量,而不仅仅是 $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从WP_Query()构造SQL的方式来看,我认为这是不可能的:查询变量没有OR'ing或UNION。

我唯一想到的是编写一个插件来实现

posts_where
过滤器(应用于返回 post 数组的查询的 WHERE 子句)。您可以使用不同的 WP 查询来调用此插件,该插件将获取它们的
WHERE
部分,并可以
OR
将它们组合在一起。

另请参阅 http://codex.wordpress.org/Custom_Queries

© www.soinside.com 2019 - 2024. All rights reserved.