s How to make WordPress Custom Post Types work on Category Pages

Getting WordPress Custom Post Types to work on Category Archive Pages

Getting WordPress Custom Post Types to work on Category Archive Pages

I’m sure many of you are familiar with the awesomeness that is WordPress custom post types. For those who aren’t, since WP 3.0, we’ve had the capability to add and use custom post types in a variety of different ways. Stored inside the wp-posts table, with a unique post_type identifier, creating custom post types is a really powerful way to separate out different types of content on your website.

There’s a ton of plugins out there to help you create your own custom post types, if you don’t feel like registering them yourself via your functions.php file – it all depends on what it is you’re attempting to do.

One universal issue I have found, which seems to have befouled a great many WP Developers and Designers is that regardless of how you’ve gone about creating your custom post type, the damn things just won’t play nice with your archive or category pages.

This is caused by your archive and category pages only querying items from the wp_posts table for posts of the “post” type, and therefore, when you create a new custom post called “books” for example and drop that into a category, when you view the category page you’ll be informed by wordpress that there’s nothing posted inside that category. Thanks for that.

The Fix!

Fear not, there is a super simple solution that’ll get posts of any type displaying inside your category, archive or tags templates. Just drop this little baby into your functions.php file, replacing “YOUR-POST-TYPE” with your own custom post type.

Job’s a good’un. 🙂

1
2
3
4
5
6
7
8
9
10
function my_get_posts( $query ) {

if ( is_category() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'page', 'YOUR-POST-TYPE' ) );

if ( is_tag    () && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'page', 'project' ) );

return $query;
}

 

Leave a Reply

Enjoyed this article?

If you enjoyed this article please rate & share.

You Might Also Like