Getting WordPress Custom Post Types to work on Category Archive Pages

Bish
Bash
Boshanka
Let's get it done!

0 Shares

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;
}

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
Bish
Bash
Boshanka
Let's get it done!

Based in London, Working Everywhere

I’m a Freelance Web Designer and WordPress developer, I’m based in London but work with client’s in the UK and all over the world.

Creative Web Design & WordPress Development Services