How To: Enable Pagination in WordPress With Number of Posts Per Page


Pagination is hard to achieve and it’s a well worth time spent to enable this feature on WordPress blogs. At times, we may need to show a set of posts which belong to a particular Category in a single page. This is easy to achieve as we create a new page and embed the following code to display all the posts within a particular category.

<?php query_posts('cat=7&&showposts=10'); ?><br />
<ul><br /><?php while (have_posts()) : the_post(); ?><br />
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?>
</a></li><br /><?php endwhile;?>

The above code displays 10 recent posts from the Category with an id=7.

Now, what if this particular Category had 30 posts and we wish to display these 30 posts in a count of 10 each on one page each. That is, these 30 pages would come on Page 1, Page 2, Page 3 with first 10 posts on Page 1 and Second set of 10 posts in Page 2 and finally the third set of 10 posts in the Page 3.

Let’s try to achieve it now.

Most of the times, the code used to achieve the feat of getting a few posts per page results in page moving forward, but the posts remain the same in every page.

Just try the following code in order to achieve what we need.

<?php if (have_posts()) : ?>
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("category_name=somecat&paged=$paged"); ?>
<?php while (have_posts()) : the_post(); ?>

Change the category_name to the name of the category for which you wish the posts to be paginated.

Let me know if you have any problems using this.

Blog Widget by LinkWithin

4 Comments

  1. This was very helpful. Thank you!
    Michael Lynch´s last [type] ..Robert Ramsay

  2. Sal Michaels says:

    Thanks for this. Do you have any idea how to extend this option a bit further and provide the user with the ability to choose the number of posts they would like to see on the first page? For instance, like most eCommerce sites, you would have a drop down, or button that allowed you to view 20, 50, 100 or All posts associated with a page? I tried searching for plugins, but doesn’t seem like one exists.

    Any help?

    Sal

    1. Daniel Noll says:

      I came here wondering this as well. For example on a category archive Page 1, display 5 posts while on all successive pages (Page 2, 3, etc.) display 10 posts.

  3. ARS says:

    Great! This is exactly what I’m looking for long time. Thanks!!

Leave a Reply

CommentLuv badge