2013-11-27 83 views
1

我正在構建一個主頁的模板,其中顯示了頂部的4個最新帖子以及頁面周圍按類別劃分的一些帖子組(我使用get_posts執行查詢)。從wordpress自定義查詢中排除重複的帖子

我想要做的就是從這些類別的帖子中排除已經出現在最新的四條新聞中的任何帖子。

我想我應該得到這四個職位ID,並在「類別」查詢中使用'post__not_in'參數,但我無法使其工作。

你有什麼提示嗎?

這是代碼:

// First query: I get last four posts 

$args = array(

    'post_type'  => 'post', 
    'post_status'  => 'publish', 
    'numberposts'   => 4 

); 

// In my dreams, this should be the array of post IDs 

$ids->query_vars['page_id']; 

// Second query: I get 5 posts for a given categoory and exclude posts with IDs from first query 

$query = new WP_Query($args); 

$args2 = array(

    'numberposts' => 5, 
    'category'   => 15, 
    'orderby'   => 'post_date', 
    'order'   => 'DESC', 
    'post__not_in' => $ids 

); 
$query2 = new WP_Query($args2); 

$primaposizione = get_posts($args2); 
foreach ($primaposizione as $post) : setup_postdata($post); 

... do the stuff ... 

endforeach; 
wp_reset_postdata(); 

UPDATE

<?php 
    $args = array(
    'post_type'  => 'post', 
    'post_status'  => 'publish', 
    'orderby'   => 'post_date', 
    'order'   => 'DESC', 
    'posts_per_page'   => 4 
    ); 

    $query = new WP_Query($args); 
    $excludeID = array(); 
    while ($query->have_posts()) : $query->the_post(); 
    $excludeID = $post->ID; 
    endwhile; 

     $args = array(
      'posts_per_page' => 1, 
      'orderby'   => 'post_date', 
      'order'   => 'DESC', 
        'category'   => 15, 
      'post_type'  => 'post', 
      'post_status'  => 'publish', 
      'post__not_in' => array($excludeID) 
     ); 

     $primaposizione = get_posts($args); 
     foreach ($primaposizione as $post) : setup_postdata($post); 
     $category = get_the_category(); 
     $slug = $category[0]->category_nicename ; 
     $esteso = $category[0]->cat_name; 
     if(has_post_thumbnail()) { ?> 
      <span class="hidden-xs"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('bones-thumb-300', array('class' => 'img-responsive')) ?></a></span> 
      <?php } ?> 
      <h3 class="ellipsis"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> 
      <?php the_excerpt();?> 
     <?php endforeach; 
    wp_reset_postdata(); 
?> 
+0

你在正確的軌道上。請張貼一些代碼進行評論。 –

+0

你說得對,我只是粘貼了我的代碼。 – digitalfaber

回答

0

的方式你想選擇的ID是行不通的。你必須先調用wp_query。我想,這應該工作:

$args = array(
    'post_type'  => 'post', 
    'post_status'  => 'publish', 
    'numberposts'   => 4 
); 

$query = new WP_Query($args); 
$excludeID = array(); 

while ($query->have_posts()) : $query->the_post(); ?> 
    $excludeID[] = $post->ID;  // forgot the brackets 
    // do stuff 
endwhile; 

(...)

+0

感謝Koen,我想我越來越近了,但我仍然錯過了一些東西:我只得到第四篇文章的ID而不是數組。 我可能在語法上做錯了什麼。 你介意看看我粘貼的更新代碼嗎? – digitalfaber

+0

對不起,我在$ excludeID後忘了括號。將其更改爲$ exclude [] = $ post-> ID;並刪除數組()在這裏'post__not_in'=> $ excludeID –

+0

它的作品像一個迷人的;) 謝謝你Koen! – digitalfaber

相關問題