简体   繁体   中英

Wordpress Limit posts on home page

I am developing a wordpress blog but for some reason the posts won't limit on the home page. I am trying to limit to 3 but it falls back to what is set in the administration area instead of 2. How come?

What am I doing wrong?

<?php
        $temp = $wp_query;
        $wp_query = null;
        $wp_query = new WP_Query('posts_per_page=-1&paged=' . $paged);
        query_posts('showposts = 2');
        $flag = 1;
        while ($wp_query->have_posts()) : $wp_query->the_post();
    ?>

Try using this code in the functions.php to limit the posts on the homepage, it should limit the posts to 2:

function posts_on_homepage( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 2 );
    }
}
add_action( 'pre_get_posts', 'posts_on_homepage' );

There are 2 option available to do your task, you can easily limit post on your home page.

1) From the Dashboard:

(a) Settings->

(b) Reading ->

(c) Blog Posts - set to 3

Or you can do this....

2) From the Dashboard:

(a) Appearance

(b) Editor

(c) home page file (usually index.php)

(d) Locate this line:

(e) Just before this line add this line:

I hope this process will work for you, if you need more help I'm always available to help you

You cannot use WP_Query and query_posts together. And you should never use query_posts . You should either use pre_get_posts or WP_Query .

You should set posts_per_page to 3 if you need to display 3 posts.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM