2009-08-28 66 views
3

在Wordpress中,可以爲循環創建自己的WP查詢。一個例子是這樣的:Wordpress - 將多個WP Query對象合併成一個?

$my_query = new WP_Query(array('post_parent' => 3, 'post_type' => 'page')); 

另一個例子是這樣的:

$my_query = new WP_Query(array('cat' => 1, 'post_type' => 'post')); 

我想要一個循環,呈現來自同一循環頁和帖子。

現在我的問題。是否有可能將這兩個對象合併爲一個?如果是,如何?我不想創建兩個不同的循環。

回答

2

我找到了自己的解決方案。我使用setup_postdata來解析SQL查詢。

The solution

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' 

從查看源和the way WP constructs SQL from WP_Query(),我不認爲這是可能的:沒有的OR'ing查詢瓦爾的UNION也不。

我唯一想到的就是編寫一個實現posts_where篩選器的插件(應用於查詢的WHERE子句,它返回的是帖子數組)。你可以使用不同的WP Querys來調用這個插件,並且這個插件會得到它們的WHERE部分,並且可以將它們一起使用OR

又見http://codex.wordpress.org/Custom_Queries

+0

我發現我的解決方案這個時候使用setup_postdata作爲SQL語法分析程序(見我自己的答案)。您的替代方案可能對未來有所幫助。感謝您給我一個替代解決方案! – 2009-08-30 09:07:34

1

如果你不想用SQL做到這一點,這就是我做我的搜索頁面。

基本問題:當進行meta_query時,wordpress認爲我希望條件以「AND」而不是「OR」加入。

所以Wordpress尋找標題/內容=「myContent」和aioseop_keyword「myContent」的頁面。這(在我的情況下)導致零結果,儘管有一個與SEO關鍵字匹配的頁面。

爲了解決這個問題,我做了兩個查詢。聽起來很簡單,但是:儘管在$ post對象中有帖子,但Loop不想識別帖子。在看過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>'; 
} 
相關問題