問題描述
如何從 WP_Query 查詢中排除一個特定的帖子? (例如,顯示 ID 為 278 的帖子除外)
我已經嘗試了 post__not_in 引數,但它只是刪除所有的帖子..
任何幫助都會很棒。
這是我當前的查詢
<?php
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query(array(
'post_type' => 'case-study',
'paged' => $paged,
));
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
謝謝
最佳解決方法
我想這很重,但是為了回答你原來的問題,我收集了第一個迴圈中的所有帖子的陣列,並從’post__not_in’ 中排除了第二個迴圈中的這些帖子,這個’post__not_in’ 需要一個 post id 的陣列
<?php
$args1 = array('category_name' => 'test-cat-1', 'order' => 'ASC');
$q1 = new WP_query($args);
if($q1->have_posts()) :
$firstPosts = array();
while($q1->have_posts()) : $q1->the_post();
$firstPosts[] = $post->ID; // add post id to array
echo '<div class="item">';
echo "<h2>" . get_the_title() . "</h2>";
echo "</div>";
endwhile;
endif;
/****************************************************************************/
// array of post id's collected in first loop, can now be used as value for the 'post__not_in' parameter in second loops query $args
$args2 = array('post__not_in' => $firstPosts, 'order' => 'ASC' );
$q2 = new WP_query($args2);
if($q2->have_posts()) :
while($q2->have_posts()) : $q2->the_post();
echo '<div class="item">';
echo "<h2>" . get_the_title() . "</h2>";
echo "</div>";
endwhile;
endif;
?>
第一個迴圈顯示類別中的所有帖子,並將帖子 ID 收集到陣列中。
第二個迴圈顯示所有帖子,不包括第一個迴圈中的帖子。
次佳解決方法
您正在尋找的引數是 post__not_in(凱撒在他的答案中有打字錯誤) 。所以程式碼可能就像:
<?php
$my_query = new WP_Query(array(
'post__not_in' => array(278),
'post_type' => 'case-study',
'paged' => $paged,
));
while ($my_query->have_posts()) : $my_query->the_post(); endwhile;
第三種解決方法
您必須將 post__not_in arg 定義為陣列。即使是一個單一的價值。請不要用臨時東西覆蓋全域性核心變數。
<?php
$query = new WP_Query( array(
'post_type' => 'case-study',
'paged' => $paged,
'post__not_in' => array( 1, ),
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do stuff
} // endwhile;
} // endif;
?>
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。