Correct Pagination with get_posts

If you like to show your posts a little bit different on your homepage or category page. For example having a different amount of posts showing on these pages, as it is set in your admin, you will get a problem with the pagination function. Because WordPress and several paging Plugins use $wp_query->max_num_pages.

max_num_pages is the result of available posts divided by the set number of posts per page. For example we set 10 posts per page, but we have on our starting page 14 posts, it will mess up the pagination.

My solution works with the WordPress pagination and looks like this:

//detect the set number of posts per page
$ppp = get_option('posts_per_page');

// first page 14 posts
if (!is_paged()) {
    $posts = get_posts('numberposts=14');
// second page with offset
} elseif($paged == 2) {
    $posts = get_posts('offset=14');
// all other pages with settings from backend
} else {
    $offset = $ppp*($paged-2)+14;
    $posts = get_posts('offset='.$offset);

if($posts) :
    foreach ($posts as $post) :
        //your code 

This might be not the most intelligent solution, but it works. If anybody has a better idea, please let us know in the comments.





4 responses to “Correct Pagination with get_posts”

  1. […] Correct Pagination with get_posts – $wpquery->maxnumpages, WordPress, This, Plugins, Because – WP Engineer Correct Pagination with get_posts – $wpquery->maxnumpages, WordPress, This, Plugins, Because – on WP Engineer. […]

  2. Sakib Avatar

    I wish you have seen tons of website, using “next” and “previous” button – if you want to read a complete post, you have to click several times to the “next” button. How I can implement this features on my weblogs and with big posts? Do you please response. that will be really great, if I get a good solutions.

  3. aleem Avatar

    The above idea is correct to some extent but cannot work exactly. for pagination, you should define a separate class and locate in theme or plugin directory.

    Now i am also working on pagination, i applied so many approaches but still i am unable to paginate the comments, written by users.

  4. Scotty Avatar

    Hmm. This doesn’t seem to be working for me. I wanted to display 2 posts on the first page, then 10 on each page afterwards.

    I seem to get the first 2 posts on the first page, then only 1 post on the second page :S All the rest of my posts aren’t visible.

    Any ideas? I’m using the latest version of WordPress (2.9.1)