#22299 closed defect (bug) (invalid)
posts_per_page value in $wp_query does not work in index.php
Reported by: | alexvorn2 | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | |
Component: | Query | Keywords: | close |
Focuses: | Cc: |
Description
For example we have only 2 posts.
Using this code to display only one post (title) per page:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'posts_per_page' => 1, 'paged' => $paged ); // The Query $the_query = new WP_Query( $args ); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); echo '<li>'; the_title(); echo '</li>'; endwhile; // Reset Post Data wp_reset_postdata();
I inserted this in index.php
Going to page/2 will show an error instead of the page 2 (with one post title) of the actual query. I suspect that this is a bug or I missed something?
Change History (6)
#2
in reply to:
↑ 1
@
12 years ago
Replying to SergeyBiryukov:
pre_get_posts
hook should be used instead.
we can use like this
function hwl_home_pagesize( $query ) { $query->query_vars['posts_per_page'] = 1; return; } add_action('pre_get_posts', 'hwl_home_pagesize', 1);
But this will be like a global function that will apply the same settings to all loops, not good. Why not just update "posts_per_page" option with "1"?
This is a bug 100%
#3
follow-up:
↓ 4
@
12 years ago
You can add $query->is_main_query() && $query->is_home()
check there:
function hwl_home_pagesize( $query ) { if ( $query->is_main_query() && $query->is_home() ) $query->query_vars['posts_per_page'] = 1; return; } add_action('pre_get_posts', 'hwl_home_pagesize', 1);
This is actually a support issue.
#4
in reply to:
↑ 3
@
12 years ago
Thanks! But this does not work for me.
I'm working on a drag and drop feature for a theme, so I'm using wp_query OR query_posts() [for me they are the same] in a widget, that I'm integrating it in the 'general template' that shows in the home and all archives pages.
And in the settings of the widget there is a such option as post per page...
And using an action, seems not a good idea, because I might use TWO or more loops on the same page (divided by different categories)...
Hope a core developer would come to the same problem as I in the near future.
#5
@
12 years ago
- Milestone Awaiting Review deleted
- Resolution set to invalid
- Status changed from new to closed
Pagination is calculated before the template is loaded. This is basically the same as using query_posts(), but since you are also altering posts_per_page, then using 'paged' isn't enough, because *total* pages was calculated against the original, main one.
pre_get_posts
hook should be used instead.See #11067, #16168, #16450, #19463.