Customizing a WordPress site with custom post types can be a wonderful thing. Custom post types make it possible to do things that could not be done with earlier versions of WP. I recently had a project where I implemented this new feature and feel it is worth sharing how I got everything to work.
I was building a site for a greeting card company and I wanted to make some things as easy to do as possible. For example, they wanted their site sectioned off in three areas: Announcements, Press Releases, and blog posts. I chose to use custom post types for the Announcements and Press Releases so the end user wouldn’t have to remember to maybe categorize posts in a certain way to get them to display in the proper sections of the site.
One of the goals of this site was to keep these types of posts separate, so I created two custom page templates to handle displaying all the posts for each custom post type. That was easy enough; all it takes is a custom loop that only calls for posts of a certain type:
<?php $loop = new WP_Query( array( 'post_type' => 'announce', 'paged'=>$paged ) ); ?> <?php custom_query_posts(); ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
Getting custom post types to display on a custom page wasn’t an issue, but getting these custom types to paginate has been a problem for many people. I first ran into the issue where the “next” and “previous” links wouldn’t show, and then they would show and not be links. I tried some solutions I found online, but kept coming up blank.
What finally did work for me was this little snippet of code that I inserted into my theme’s functions.php file:
function custom_query_posts(array $query = array())
{
global $wp_query;
wp_reset_query();
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$defaults = array(
'paged' => $paged,
'posts_per_page' => PER_PAGE_DEFAULT
);
$query += $defaults;
$wp_query = new WP_Query($query);
}
After adding this section of code, the pagination links showed up and worked perfectly. There were no 404 errors and there was no mixing of the custom post types. And if you look at the modified loop I used to call only the custom post type, you’ll see that I used this custom_query_posts function.
If you’re struggling to get your WordPress custom post types to paginate properly, give this code a try and see if it works for you. If this doesn’t work for you, what have you done to get your custom types to display the way you want?
No related posts.
{ 4 comments… read them below or add one }
Ive been looking for a solution to getting my custom posts to paginate also.. Im still unsuccessful.. Im surprised its such a hard task
I will try this method, I’ve been digging the whole wordpress world for the custom page pagination but still no luck…
What is the purpose of creating the second instance of WP_query?
http://wordpress.org/support/topic/pagination-with-custom-post-type-listing
Here is a forum thread explaining a little bit more about the function