WordPress Custom Post Types: Archive Pages

Don’t you hate it when you’re banging your head against a problem you’ve already solved? When you forget one key piece of information that unlocks the problem in an instant?

In this case, I set up a site with custom WordPress post types (in this case “Projects”), and I was trying to create category archive pages to display project teasers. I created a Thesis category page, set up my WP loop and post box, and headed over to view my creation. Nada. Nothing. Zilch. No custom post types. No projects.

Cue gnashing of teeth and scurrying around like a lunatic trying to work out what I’d done wrong…until I remembered one key piece of information. Registering a custom post type in WordPress does not automatically add it to the main query. Once more, with emphasis:

Registering a custom post type in WordPress does not automatically add it to the main query

I’d come across this issue before, and had a ready made code snippet. Add this custom function, and problem solved:

/**MAIN QUERY: CUSTOM POST TYPES**/
// Show posts of 'post', 'page' and 'project' post types in the main query
// Doesn't fire on admin pages or blog (home) page
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
	if ( ! is_admin() && ! is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', 'page', 'project', 'people' ) );
	return $query;
}

Problem solved – custom post types now appear in category pages.

For more info, check out the relevant article about custom post types in the WordPress Codex.