2016-11-28 56 views
0

我正在嘗試使用wp_query構建查詢,其中某些帖子ID必須排除。以下是我正在使用的代碼:Wp_query post__not_in無法正常工作

$args = array('posttype' => 'post', 'posts_per_page' => 1, 'cat' => 14, 'post__not_in ' => array(71,1), 'orderby' => 'menu_order', 'order' => 'ASC' , 'post_status' => 'publish'); 
$the_query = new \WP_Query($args); 

但是wp_query仍然向我返回帶有這些ID的帖子。

以下是帶有wp_query對象http://pastebin.com/gjayN4Yc的pastebin。 至於我遇到下面的wp_query->要求:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND (wp_term_relationships.term_taxonomy_id IN (14,15)) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC LIMIT 0, 3 

我做得不對或這是一個核心的錯誤?

謝謝。

回答

1

我運行了你的代碼,它對我很好,除了'post__not_in '之後有一個額外的空間。你看到了嗎?確保你有密鑰'post__not_in'

此外,還有幾件事情提:

  1. 'post_type'而不是'posttype
  2. 'menu_order'不適用於帖子。這是分配給分級職位類型的,例如pages。您可以在Page Order UI中設置該字段,該字段對於帖子不可用(默認情況下)。

下面是修改後的代碼:

$args = array(
    'post_type'  => 'post', 
    'posts_per_page' => 1, 
    'cat'   => 14, 
    'post__not_in' => array(71, 1), 
    'orderby'  => 'date', 
    'order'   => 'ASC', 
    'post_status' => 'publish', 
); 
$the_query = new WP_Query($args); 
if (! $the_query->have_posts()) { 
    // maybe echo a message that none were found 
    return; 
} 

while($the_query->have_posts()) { 
    $the_query->the_post(); 

    // do your business logic here 

    // then call the view file to render the HTML 
} 
wp_reset_postdata(); 

SQL查詢就變成了:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 
FROM wp_posts 
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
WHERE 1=1 AND wp_posts.ID NOT IN (71,1) AND 
      (wp_term_relationships.term_taxonomy_id IN (14)) AND 
      wp_posts.post_type = 'post' AND 
      ((wp_posts.post_status = 'publish')) 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.post_date ASC LIMIT 0, 1 
0

您是否嘗試過在$args數組鍵添加第二個下劃線post後 - 所以它的post__not_in(2連續的下劃線),而不是post_not_inthe WP_Query docs

+0

你好,不知何故而將其粘貼過來錯但在源代碼中就像你說的那樣。 –

+0

這感覺更像是一個評論,而不是一個答案.... –

0

試試這個

$aTest = new WP_Query(array( 
          'post_type'  => 'post', 
          'posts_per_page' => -1, //all post 
          'order'   => 'ASC', 
          'cat'   => 14, 
          'post__not_in' => array(27), 
          'orderby'  => 'date', 
          'post_status' => 'publish' 
          )); 
while ($aTest ->have_posts()) : ($aTest ->the_post()) ; 
$aTest Image  = wp_get_attachment_url(get_post_thumbnail_id($post->ID)); 
$title   = get_the_title(); 
$content   = get_the_content(); 
endwhile;