Including Custom Posts on Archive Pages in WordPress

- by

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') );
  }
}
if (!is_admin() {
  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).

Note that the hook will not be executed when the search is executed in the admin area. Doing so will show an “invalid post type” error.

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



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.