How to change loop times in WordPress

GOAL

To stop the loop at the number of times specified in WordPress.

Environment

WordPress 5.5.1

Loop in WordPress

The Loop is PHP code used by WordPress to display posts. The following is an example of the loop.

<?php 
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post(); 
		//
		// Post Content here
		//
	} // end while
} // end if
?>

Check “The Loop” in wordpress.org for details about the loop.

Method

Use get_posts function

<?php
	$recentposts = get_posts( array( 'posts_per_page' => 3) );
	if ( $lastposts ) {
    		foreach ( $lastposts as $post ) : setup_postdata( $post );
			the_title();
        		//
			// Post Content here
			//
		endforeach; 
    		wp_reset_postdata();
	} //end if
?>

Appendix

Though <?php query_posts(‘posts_per_page=NUMBER’); ?> can be also used to limit the number of posts, it is not recommended.