2016-10-26 188 views
1

在顯示單個帖子的頁面上,我也希望顯示一些精選帖子。循環內循環 - wordpress

特色的帖子有一個元值賦予他們區分精選和非精選帖子。

問題是我希望在我的頁面中間顯示特色文章,但循環從頂部開始,直到頁面底部才完成。

從WP文檔:

<?php 
    // The main query. 
    if (have_posts()) { 
     while (have_posts()) { 
     the_post(); 
     the_title();                
     the_content();               
     } # End while loop                
    } else {                  
     // When no posts are found, output this text.       
     _e('Sorry, no posts matched your criteria.');       
    }                 
    wp_reset_postdata();               

    /*                   
    * The secondary query. Note that you can use any category name here. In our example, 
    * we use "example-category".            
    */                   

    $secondary_query = new WP_Query('category_name=example-category');   

     // The second loop. 
    if ($secondary_query->have_posts()) { 
     echo '<ul>'; 
     // While loop to add the list elements. 
     while ($secondary_query->have_posts()) { 
      $secondary_query->the_post(); 
      echo '<li>' . get_the_title() . '</li>'; 
     } 
     echo '</ul>'; 
    } 
wp_reset_postdata(); 
?> 

在第一循環結束時,你必須調用wp_reset_postdata()但在我的情況,有需要被下跌的一頁,所以我不能再檢索數據結束它。

我基本上需要這樣做,但只有特色的帖子得到渲染,而不是帖子本身。

if (have_posts()) { 

    while (have_posts()) { 
     the_post(); 
     the_title();                
     the_content();               

     //Display featured posts half way through 
     $secondary_query = new WP_Query('category_name=example-category'); 
     //end featured post loop 
     wp_reset_postdata(); 

     //continue outputting data from first loop 
     the_title(); 
    } # End while loop.                 

} else {              
    // When no posts are found, output this text.       
    _e('Sorry, no posts matched your criteria.');       
} 

//finally end inital loop               
wp_reset_postdata(); 

是否有可能'暫停'循環做一個不同的循環,然後再選擇它回來?

回答

1

通常您的第二個代碼示例應該可以工作。您不必呼叫wp_reset_postdata()來結束主循環,只需調用它即可結束次循環。

使用此函數可以在使用新WP_Query的輔助查詢循環後恢復主查詢循環的全局$ post變量。它將$ post變量恢復到主查詢中的當前帖子。


您還可以使用get_posts()此:

$secondary = get_posts(array(
    'posts_per_page' => 5,   
    'category_name' => 'example-category', 
    'orderby'   => 'date', 
    'order'   => 'DESC',  
    'meta_key'   => 'featured_posts', 
    'meta_value'  => 'yes', 
    'post_type'  => 'post',  
    'post_status'  => 'publish',   
)); 

if (count($secondary)) { 
    echo '<ul>'; 
    foreach ($secondary as $entry) { 
     // print_r($entry); exit; 
     echo '<li>' . $entry->post_title . '</li>'; 
    } 
    echo '</ul>'; 
}