2013-02-08 63 views
0

我按照自定義字段值的降序排列帖子,我想知道是否有方法按降序查找第n個帖子。WordPress的 - 如何獲得循環的第n個職位?

例,順序是:

1st from top: id = 9 
2nd from top: id = 5 
3rd from top: id = 6 

現在,我使用get_template_part()顯示帖子。

我想知道是否有什麼東西get_template_part_of_post(3rd-from-top)

<div class="onethird"> 

        <?php 


        $count_posts = wp_count_posts("ott_products", ""); 
        $published_posts_orig = $count_posts->publish; 
        $published_posts = $published_posts_orig + (3 - ($published_posts_orig % 3)); 


        $i = 0; 

        if (have_posts()) : while($query->have_posts()) : 

         echo $i . " " . $published_posts; 
         $i = $i + 3; 
         $query->the_post(); 

         get_template_part('content', 'category'); 

         if ($i % 3 === 2) : 
          if (($i - 2 == $published_posts)) : 
           $i = 3; 
         endif; endif; 

         if ($i % 3 === 1) : 
          if (($i - 1 == $published_posts)) : 
           echo "</div><div class='onethird last'>"; 
           $i = 2; 
         endif; endif; 

         if ($i % 3 === 0) : 
          if (($i == $published_posts)) : 
           echo "</div><div class='onethird'>"; 
           $i = 1; 
         endif; endif; 


        endwhile; 

        else : 

         get_template_part('no-results', 'archive'); 

        endif; 

        ?> 


      </div> 

這就是我目前使用的。這將帖子分成三列。

變量i將從上到下的三列變爲從左到右。

以前,我有顯示類似的帖子:

(Total 9 posts) 
1 4 7 
2 5 8 
3 6 9 

有了它,我得到的i到:現在

(Total n posts) 
1 2 3 
4 5 6 
... 

,問題是,我不能讓i日發佈顯示。帖子仍然進來第一順序。

回答

0

您可以先使用total_posts = wp_count_posts()來計算帖子數量。

然後你必須運行「循環」,並保持對每個崗位的計數器,當該計數器命中TOTAL_POSTS - N,執行所需的操作:

僞代碼:

total_posts = wp_count_posts(); 
count = 0; 
while(have_posts()) { 
    count++; 
    if (count = total_posts - N) { 
     // ACTION  
    } 
    the_post(); 
} 
+0

感謝您的答案,我編輯了上面的代碼,以解釋爲什麼這不起作用。 – NamanyayG 2013-02-08 16:05:13

0

get_template_part()完全按照它的說法,它會獲取位於主題文件夾中的模板。它接受的唯一參數是slu and和名稱(請參閱WordPress codex

如果我理解正確,您希望每次獲取第3篇文章?最簡單的方法是在模板文件中設置一個計數器和條件,可能是loop-something.php

$i = 0; 

if (have_posts()): 

while (have_posts()) : the_post(); 

    if ($i % 3 == 0): 
    // Do something different, this is the first column. 
    // I propose: 
    $column = 1; 

    elseif ($i % 3 == 1): 
    // Do something different, this is the second column. 
    $column = 2; 

    elseif ($i % 3 == 2): 
    // Do something different, this is the third column. 
    $column = 3; 
    endif; 

    echo '<div class="column-'.$column.'">'; 
    // the post 
    echo '</div>'; 

    $i++; 

endwhile; 

else: 

    get_template_part('no-results', 'archive'); 

endif; 
+0

非常感謝您的回答,但是使用我當前的設置,這不起作用。編輯答案來解釋原因。我想要'get_post(i);'這樣的東西。 – NamanyayG 2013-02-08 16:06:01

+0

編輯我的答案。不過,我建議不要太依賴HTML來構建列。使用一些CSS :) – 2013-02-08 16:21:43

1

得到nth後最簡單的方法是做這樣的事情:

global $posts; 

// This gets your nth level post object. 
if(isset($posts[ $nth_post ])) 
    echo $posts[ $nth_post ]->post_title; 

我希望這有助於。 :)

相關問題