Home Custom Query Pagination, Custom Post Type Pagination – A working solution.
Post
Cancel

Custom Query Pagination, Custom Post Type Pagination – A working solution.

Instead of using query_posts, use a hook pre_get_posts. Read more over at http://www.billerickson.net/customize-the-wordpress-query/

Custom Query Pagination

I often only want to display certain categories or a custom post type and have had a lot of problems with displaying a custom query pagination or custom post type pagination. In my last post I have showed you how to simple add a [beautiful pagination with WP-PageNavi](https://schurpf.com//wordpress-pagination-how-to-paginate-in-wordpress/ “WordPress PaginationHow to paginate in WordPress”). In this post I will be showing you how to add a more complex pagination for custom post types and categories. There are a lot of solutions out there, several using the variable WP_Query or even querying the database itself. Let me share with you how I do custom query pagination with the following example.

Example custom query pagination

Goal of code below is to display all but category with id 3. (To find ids of categories go to post->categories->CategoryName and check the address bar for its id).
[code]

<?php $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$args= array(
‘cat’ => -3,
‘paged’ => $paged,
);?>
<?php query_posts( $args );?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

…[/code]
This is it. There are two things to note. The first one is the first line where I retrieve the variable paged or set it to 1 if it doesnt exist. The second thing to note is that I use query_posts while passing it the variable paged as argument. This is it. Simple as that.

Example custom post type pagination

[code]

<?php $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$args= array(
‘post_type’ => ‘YourCustomPostType’,
‘paged’ => $paged,
);?>
<?php query_posts( $args );?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>


[/code]

Please replace YourCustomPostType with your custom post type slug. This is essentially the same as above, the only thing changes is the argument passed to query_posts. That is it. Nothing else, nothing more.

Custom Query Pagination, Custom Post Type Pagination – posts_per_page

I have found that as soon as I set posts_per_page I run into very strange behavior (i.e. it doesnt work). I try to avoid using posts_per_page and rather set the number of posts via:
Settings->Reading-> Blog pages show at most x posts
Where I set number x to what I want. That way I can use the custom query pagination as described above and dont have to worry about anything.

Hope this helped you. Please leave a comment if anything is unclear or you simply want to thank me (I like that 🙂 ). Also consider signing up to my newsletter to receive similar valuable information.

This post is licensed under CC BY 4.0 by the author.
Trending Tags