What do I need to do to see only 5 most recent posts in my index page on wordpress?
I have this loop:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
and I tried to sweach it with that:
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
and it only returned errors. What do I need to do?
Try this way instead:
<?php
function five_posts_on_homepage( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 5 );
}
}
add_action( 'pre_get_posts', 'five_posts_on_homepage' );
if (have_posts()) : while (have_posts()) : the_post();
?>
If there a particular reason you have to do it code? Otherwise, you really should just use the Admin Settings.
Under Settings -> Reading, there is a "Blog pages show at most" option where you can change it to 5 pages (see screenshot below).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.