How to Display Any Number of Posts in a WordPress Loop


The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Normally, the number of posts to be displayed is set in your WordPress Admin Panel Settings area under the readings tab. But in this article, we will show you how to override that number by using a Super Loop which will allow you to display any number of posts in that specific WordPress loop. This will allow you to customize the display of your pages including author profiles, sidebars, and more.

Open a template file where you would like to place the posts and then simply add this loop:

// if everything is in place and ready, let's start the loop     <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>    // to display 'n' number of posts, we need to execute the loop 'n' number of times  // so we define a numerical variable called '$count' and set its value to zero  // with each iteration of the loop, the value of '$count' will increase by one  // after the value of '$count' reaches the specified number, the loop will stop  // *USER: change the 'n' to the number of posts that you would like to display    <?php static $count = 0;  if ($count == "n") { break; }  else { ?>    // for CSS styling and layout purposes, we wrap the post content in a div  // we then display the entire post content via the 'the_content()' function  // *USER: change to '<?php the_excerpt(); ?>' to display post excerpts instead    <div class="post">  <?php the_title(); ?>  <?php the_content(); ?>  </div>    // here, we continue with the limiting of the number of displayed posts  // each iteration of the loop increases the value of '$count' by one  // the final two lines complete the loop and close the if statement    <?php $count++; } ?>  <?php endwhile; ?>  <?php endif; ?>

And you are done. This code will be very helpful to you specially when designing the author’s template because you would want to control the number of posts displayed in each loop.

Source: Super Loop for WordPress

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.