Wordpress,循环:只显示2个帖子

时间:2011-03-19 16:01:50

标签: php wordpress

在循环中只展示2个帖子的最佳方法是什么?

<?php
$i = 1;
while (have_posts()):
    if ($i == 3)
    {
        break;
    }
    the_post();
    $i++;
endwhile;
?>

还有更“美丽”的东西吗?

4 个答案:

答案 0 :(得分:7)

使用query_posts()

query_posts('posts_per_page=2');
在循环之前

摘自文档页面:

  

query_posts()可用于显示与通常在特定URL上显示的帖子不同的帖子。

答案 1 :(得分:0)

试试这个:

<?php
// Printing post number 1 and 2
for($i = 1; $i < 3; $i++){
    the_post();
}
?>

答案 2 :(得分:0)

for($i = 0; $i < 2; ++$i) {
       post_here();
}

答案 3 :(得分:0)

您可以使用WP_Query类,以避免将全局帖子与自定义循环混合

$results = new WP_Query('posts_per_page');

if ($results->have-posts()) {
    while ($results->have_posts()) {
        $results->the_post();
        the_title();
    }
}

unset($results);