2016-10-26 192 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>'; 
}