2016-10-26 26 views
1

1つの投稿を表示するページで、特集記事を表示することもできます。ループ内のループ - ワードプレス

特集記事には、特集記事と非特選記事を区別するためにメタ値が割り当てられています。

問題は、私のページの下半分の方法で投稿を表示したいのですが、ループは一番上から開始し、ページの最後までは終了しません。 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

通常、2番目のコード例が有効です。メインループを終了するにはwp_reset_postdata()に電話する必要はなく、セカンダリループを終了する場合にのみ呼び出します。

この関数を使用すると、新しいWP_Queryを使用してセカンダリクエリループの後にメインクエリループのグローバル$ post変数を復元できます。 $ post変数をメインクエリの現在の投稿に復元します。

$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>'; 
} 


また、このためget_posts()を使用することができます