DJ Quilter

Front-End Developer

Paginate Posts in WordPress

This bit of code adds pagination to a list of WordPress posts that are displayed on a page.

I’ll be honest, I think I originally found some of this code from someone on Stack Overflow. I have made a few alterations for the sites that I’ve used it on.

The below code is for a gallery page; it outputs the post thumbnail for posts in a specific category.

<div class="gallery-pagination">
<?php
// Set useful vars
$postsPerPage = 5; 
$categoryID = 5;

// Just a massive number
$big = 999999999; 

// Use $big on posts_per_page
// otherwise it'll use the posts_per_page value that is set later.
$countArgs = array('category' => $categoryID, 'posts_per_page' => $big);
$catPosts = get_posts($countArgs);
$catTotal = count($catPosts);
$paginateArgs = array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '/page/%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => ceil($catTotal / $postsPerPage));

echo paginate_links( $paginateArgs );
?>
</div>		
<ul class="category-list">
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$queryArgs = array( 'posts_per_page' => $postsPerPage, 'category' => $categoryID, 'paged' => $paged );
$allPosts = get_posts( $queryArgs );
foreach ( $allPosts as $post ) : setup_postdata( $post ); ?>
  <li>
    <h2><?php the_title(); ?></h2>
    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
    <div class="clear"></div>
  </li>
<?php endforeach; ?>
</ul>

The paginate_links function is a WordPress function, that will output your pagination wherever you echo it (so you can have it in multiple places on the page).