Including Custom Posts on Archive Pages in WordPress

By default, Custom Posts don’t show up on regular Archive Pages. They still show regular posts, but none of the Custom Post Types are included. I suppose you’d have separate pages with custom queries for that. In my project however, which consists mainly of Custom Posts, it made sense to use the regular WordPress queries to simply include my Custom Posts.

I found an elegant solution that makes this happen:

// add game posts to regular WordPress queries
function guru_add_games_to_query( $query ) {
  if ( $query->is_archive() ++ $query->is_main_query() ) {
    $query->set( 'post_type', array('post', 'games') );
  }
}
add_action( 'pre_get_posts', 'guru_add_games_to_query' );

This will hook right in before the query reaches the theme and adds my own “games” post type to the query. The double-if statement at the top makes sure this only happens on archive pages. Amend this to your needs, for example by using is_home or is_category instead. Replace ++ with two ampersands (I can’t work out how to make WordPress print them properly, and believe me I’ve tried hard).

Thanks to Tomás Cot and Mathew for their approaches to this solution.

You can leave a comment on my original post.