Wordpress loop: displaying only 2 posts

What is the best way to show only 2 posts in a loop?

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

Is there anything more "beautiful"?

+3
source share
4 answers

Use query_posts () :

query_posts('posts_per_page=2');

before the cycle.

Excerpt from the documentation page:

query_posts () can be used to display different messages than those usually displayed on a specific URL.

+7
source

Try the following:

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

You can use the WP_Query class to avoid mixing global table columns with your custom loop.

$results = new WP_Query('posts_per_page');

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

unset($results);
0
source

All Articles