2013-02-08 64 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; 

我希望这有助于。 :)

相关问题