How To Add Custom Post Pagination In WordPress

If you are using a WordPress theme that doesn’t have good pagination you can add manually. Learn how to add custom post pagination in your WordPress blog with these few simple steps.

WordPress Custom Pagination

Query CPTs

You need to write a custom query. Because when you have many posts in your WordPress blog, you need to paginate them. The following code will find all the posts of post type Article and display their titles

$article = new WP_Query( array(
 "posts_per_page" => - 1,
 "post_type" => "article" ) );
 while ($articles->have_posts()){
 $articles->the_post();
 the_title();
 echo "<br/>"; }

Now you need to use next_posts_link() to display the next page. Before you use next_posts_link() it needs to know how many pages are there. So to make it work, you’ll have to pass the number of total pages found by your query.

$total_pages = ceil( $articles->found_posts / get_option('posts_per_page') );

A WP_query object can help calculate the total number of pages via max_num_pages property.

$total_pages = $articles->max_num_pages;

Now we need that value to show the link to our next page. Just pass it to next_posts_link() like this

next_posts_link('Prevous Posts',$articles->max_num_pages)

Now it will show a valid link that can take you to the previous posts page. If your url is http://yoursite.com/articles/then, the link of the previous posts will be of this format http://yoursite.com/articles/page/2. So you’re going to need this page number in your PHP script to fetch all the posts (or CPTs) from that page. In your theme, you can get this page number using a query var called paged. The following code will correctly fetch the current page number

$current_page = get_query_var('paged') ? get_query_var('paged'):1;

To fetch all the posts from this page, you just need to rewrite your WP_Query like this

$books = new WP_Query( array(
 "posts_per_page" => - 1,
 "post_type" => "article",
 "paged" => $current_page
 ) );

In case you’d like to see a traditional pagination using page numbers, you will have to use the following code

paginate_links( array(
 "current" => $current_page,
 "total" => $articles->max_num_pages
 ) );

This way you can add custom pagination to your WordPress blog or site.

READ  How To Choose Best WordPress Hosting For Your Blog