Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using this code (below) to display posts from a category on two separate pages. The first page lists category 32 and the other lists category 31. However, on the second page it displays posts from both categories and the first page doesn't display all the posts from its category. The first page has 13 but there are only 10. The second page displays 14 but there are 19. I have no code to tell the page to only display a certain number of posts. Any idea why this is happening?

<?php
query_posts('cat=32');
while (have_posts()) : the_post();
the_content();
endwhile;
?>

I was previously using list_category_posts plug-in but I thought this was an easier solution.

share|improve this question

1 Answer 1

Firstly, avoid query_posts, instead use WP_Query or hook into pre_get_posts. query_posts is bad practice, a performance hit/slowdown, and a source of many troubles. As a fulltime developer I wouldn't very strongly recommend against all use of that function, and many prominent WordPress developers and Wordpress Core devs would say and do say the same.

The reason your code doesn't work is because query_posts redoes the query, wasting the main query, and removing all the pagination query vars included.

Instead use the pre_get_posts filter to modify the homepage, e.g. to change the number of posts on the homepage:

function hwl_home_pagesize( $query ) {
    if ( is_home() && is_main_query()) {
        //Display only 1 post for the original blog archive
        $query->query_vars['posts_per_page'] = 1;
        return;
    }
}
add_action('pre_get_posts', 'hwl_home_pagesize', 1);

http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

share|improve this answer
1  
+1. You should probably add a is_main_query() conditional for the query modification. Also, based on context of the OP, I'd assume that your first suggestion - WP_Query() - is the better approach. –  Chip Bennett Sep 23 '12 at 21:05
    
I did realize that in the Reading settings I had set it to show 14 per page. Still doesn't explain the page that only shows 13... I'm new to WordPress: looking at the reference you gave it uses is_home as the example. How do I do that for a certain page instead (ie page id 2)? –  Mowgs Ly Sep 26 '12 at 16:36
    
It's bad practice to hard code page IDs etc, and you may not be able to use the page ID as the query hasn't been built and executed yet in that hook hence the 'pre' bit, you'll need to find another queryvar to match against, such as pagename –  Tom J Nowell Sep 27 '12 at 9:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.