2016-09-08 4 views
1

これは私がwp_queryで達成しようとしているパターンです。 同じポストタイプの予定です。 wp_queryでこれを行うことは可能ですか?カスタムwp_queryループパターン

ありがとうございました!

 <div> 

      <div>1st post from featured</div> 

      <div>1st post not from featured</div> 

      <div>2nd post from featured</div> 

      <div>3rd post from featured</div> 

      <div>2nd post not from featured</div> 

      <div>3rd post not from featured</div> 

      ..and then the same pattern start again with the rest of the posts 

      <div>4th post from featured</div> 

      <div>4th post not from featured</div> 

      <div>5th post from featured</div> 

      <div>6th post from featured</div> 

      <div>5th post not from featured</div> 

      <div>6th post not from featured</div> 

      ..until there's no more post 
     </div> 

答えて

1

少し複雑になります。 2つのWP_Queryオブジェクト、いくつかの計算、およびforループが必要です。

PHPが適切な形式を知るためには、単純な形式の配列を使用できます。次の例では、カテゴリを使用して2つのWP_Queryビルドを決定します。私たちは基本変数を構築

まず、:

:我々は現在の形式の指数を計算

// Iterate every post from two queries 
    for($i = 0; $i < $posts_total; $i++){ 

れる:

<?php 

    // Build format 
    // 0 means not featured - 1 means featured. 
    $format = array(1, 0, 1, 1, 0, 0); 

    // Retrieve normal posts EXCLUDING category with ID 11 (Featured) 
    $normal_posts = new WP_Query(array(
     'post_type'  => 'post', 
     'posts_per_page' => 999, 
     'cat'   => '-11' 
    )); 

    // Retrieve featured posts ONLY INCLUDING category with ID 11 (Featured) 
    $featured_posts = new WP_Query(array(
     'post_type'  => 'post', 
     'posts_per_page' => 999, 
     'cat'   => 11 
    )); 

    // Calculate total amount of posts 
    // from our two WP_Query results 
    $posts_total = $normal_posts->post_count + $featured_posts; 

    // Setup current post index 
    $post_index = 0; 

次に、私たちは、 'ループ' または反復を開始します

 // Calculate which type of post to display based on post index 
     // We use modulo to get the right $format index 
     $post_format_index = $post_index % count($format); 
     $current_format = $format[$post_format_index]; 

最後に、正しい種類の投稿を表示してください:

 // Display to frontend based on format 
     switch ($current_format) { 
      case 1: 
       // Featured 
       $featured_posts->the_post(); 

       the_title(); 

       // Your content 

       print '<br>'; 
       break; 

      default: 
       // Not Featured 
       $normal_posts->the_post(); 

       the_title(); 

       // Your content 

       print '<br>'; 
       break; 
     } 

     $post_index++; 
    } 

?> 

これだけです。別のWP_Queryと形式を追加することで、これをさらに進めることができます。

$format = array(1, 0, 1, 1, 2, 2);