2015-09-30 159 views
1

我有兩個帖子,$ portfolio_items和$ ad_items。 每三分之一帖子應該是來自$ ad_items的帖子。 $ ad_items的帖子可以重複顯示,直到$ portfolio_items中的所有帖子都顯示出來爲止。每n個帖子添加一個特定類別的帖子

我是一個新手,當涉及到PHP,所以我很難繞過這個問題。指針和提示將不勝感激。 謝謝!

編輯: 我設法解決它,但我覺得我的代碼有點笨拙和臃腫。

<?php 
    $counter = 1; 
    $rotation = 3; 
    $ad_counter = 0; 
    $ad_id = array(); 

    $query1 = new WP_Query(array(
     "post_type" => "post", 
     "post_status" => "publish", 
     "tax_query" => array(
      array(
       "taxonomy" => "category", 
       "field" => "slug", 
       "terms" => "test", 
       "operator" => "NOT IN" 
      ) 
     ) 
    )); 

    $query2 = new WP_Query(array(
     "post_type" => "post", 
     "post_status" => "publish", 
     "tax_query" => array(
      array(
       "taxonomy" => "category", 
       "field" => "slug", 
       "terms" => "test" 
      ) 
     ) 
    )); 

    if($query2 -> have_posts()) 
    { 
     while($query2 -> have_posts()) : $query2 -> the_post(); 
      array_push($ad_id, get_the_id()); 
     endwhile; 
    } 

    if($query1 -> have_posts()) 
    { 
     while($query1 -> have_posts()) 
     { 
      if($counter == $rotation) 
      { 
       if($ad_counter >= count($ad_id)) 
       { 
        $ad_counter = 1; 
       } 
       else 
       { 
        $ad_counter++; 
       } 
       $t = get_post($ad_id[$ad_counter-1]); 
       ?> 
       <div class="post type-post status-publish format-standard hentry red"> 
        <h1> <?php echo $t->post_title; ?> </h1> 
        <p> <?php $t->post_content; ?> </p> 
       </div> 
       <?php 
       $counter = 0; 
      } 
      else 
      { 
       $query1 -> the_post(); 
       get_template_part("template/testpost"); 
      } 
      $counter++; 
     }  
     wp_reset_postdata(); 
    } 
?> 
+2

嗨@krabban,歡迎來到Stack Overflow!你能告訴我們你使用的是什麼代碼嗎?你試過什麼了? – ASCIIThenANSI

回答

0

這是一個典型的modulo task。這裏有一些僞代碼:

for ($i=0; $i<20; $i++) { 
    if (($i % 3) == 0) // do sth. 
    else // do sth. else or don't do anything at all 
} 
相關問題