It seems that pagination is a good deal of problem for a WordPress theme developer. We’ve found whole lots of issues related to the matter however it’s not that extraordinary problem. Even if you’re dealing with custom posts, you can easily implement paginations for them. Let’s find an easy way out.
In the development of custom post pagination first thing to do is to create a custom query post. If you don’t have them you certainly don’t need pagination anymore. What we write next will search posts of every type and jot down their titles.
$books = new WP_Query( array(
“posts_per_page” => – 1,
“post_type” => “book”
) );
while ($books->have_posts()){
$books->the_post();
the_title();
echo ”
“;
}
For displaying next page most of you’ll use next_posts_link(); command but unfortunately that’ll not work. This is because until now the above mentioned command has no knowledge of total number of pages. This command can work only if total number of pages is under your knowledge.
$total_pages = ceil( $books->found_posts / get_option(‘posts_per_page’) );
Another interesting way to calculate this is
$total_pages = $books->max_num_pages;
This value should be passed on to paginate next posts. Command for this is
next_posts_link(‘Prevous Posts’,$books->max_num_pages);
Now a valid link will be displayed to take you to previous or next page. Like if your url is like https://xyz.com/books/ then your previous post url will look like https://xyz.com/books/page/2. Next code will bring in the current page-number:
$current_page = get_query_var(‘paged’) ? get_query_var(‘paged’):1;
Now you need page numbers in your code for fetching all the posts from a particular page. Required code is as followed:
$books = new WP_Query( array(
“posts_per_page” => – 1,
“post_type” => “book”,
“paged” => $current_page
) );
For traditional pagination trick to work using page numbers here is the required codes:
paginate_links( array(
“current” => $current_page,
“total” => $books->max_num_pages
) );
PHP is an awesome mechanism to bring in changes at your backend and frontend functionalities. WordPress can manifest PHP’s charisma in an amazing way and there is no way to be in tension. Hope you like our above-mentioned trick. Keep on touch for more such easy shortcuts.