2017-04-15 52 views
0

我在我的網站上hace 2節:首先是針對熱門帖子(基於視圖),第二節針對最近的帖子。 如果帖子已經在熱門帖子部分,我不希望它顯示在「最近的帖子」部分。以下是我的代碼。在第一個循環中,我創建了一個數組來存儲該部分中的所有帖子ID。在第二個循環中,我檢查該數組是否在該數組中(可能不是最佳解決方案)。 由於某種原因,它只適用於第一個副本,即使$cont變爲true所需的次數(我使用echo進行了檢查)。那麼是什麼給了?WordPress的 - 不要顯示已在另一個循環中顯示的帖子

<?php 
    $popularpost = new WP_Query(array('posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' )); 
    $counter=0; 
    $post_ids = array(); 
    while ($popularpost->have_posts()) : $popularpost->the_post(); 
     $postID = get_the_ID(); 
     $post_ids[$counter] = $postID; 
    ?> 
    <a href="<?php the_permalink(); ?>" class="" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> 

    <?php $counter++; ?> 
    <?php endwhile; ?> 

    <?php $myquery = new WP_Query('posts_per_page=6'); 
    while ($myquery->have_posts()) : $myquery->the_post(); ?> 
    <?php $post_id = get_the_ID(); ?> 
    <?php $post_ids_length = count($post_ids); ?> 
    <?php for ($i=0; $i < $post_ids_length; $i++) { 
      if ($post_id == $post_ids[$i]) { 
       $cont = "true"; 
      } else { 
       $cont = "false"; 
      } 
    } ?> 
    <?php if ($cont == "true") { 
     continue; 
    } ?> 

    <a href="<?php the_permalink(); ?>" class=""><?php the_title(); ?></a> 
    <?php endwhile; ?> 

回答

2

更新你的第二個查詢如下:

$args2 = array('post__not_in' => $post_ids,'posts_per_page' => 6); 
$myquery = new WP_query($args2); 

然後就是迭代使用While循環的結果。

+0

謝謝,它的工作。但我很好奇爲什麼我的代碼沒有工作,你知道爲什麼嗎? – kulan

+0

你的代碼是錯誤的,因爲當你發現一個id等於流行的id時,你不會退出for循環,所以你繼續,如果它不是數組中的最後一個,那麼在下一個循環中$ cont變量將被設置爲false。所以你的代碼僅適用於數組中最後一個id的一個帖子。如果您添加'break',您的代碼將起作用在'$ cont =「true」;'之後' –

+0

@kulan我會推薦編寫優化代碼,如果有一個選項可以傳遞查詢本身,那麼我們不應該去執行自定義。 –