Show Custom Post Types on the Homepage

Custom post types are commonly used on WordPress sites, but they don’t show on the homepage or in the archive pages unless you write code to do that.  I’ve put together some code that is smart about detecting your public custom post types and automatically adding them to your homepage and archive pages:

/**
 * Show WordPress custom post types on the main blog and archive pages
 *
 * @param WP_Query $query
 **/
function show_custom_post_types( $query ) {

  // Show all custom post types on main blog and archive pages
  if ( $query->is_main_query() && ( is_home() || ( is_archive() && !is_post_type_archive() ) ) ) {

    $custom_post_types = get_post_types( array(
       'public' => true,
       '_builtin' => false,
    ) );
    $post_types = array_merge( array('post'), $custom_post_types );
    $query->set( 'post_type', $post_types );
   }

   return $query;
}

add_filter( 'pre_get_posts', 'show_custom_post_types' );

About

Micah is an Atlanta-based WordPress developer who is committed to continuously improving his understanding of WordPress and sharing his insights with the greater WordPress community.

2 thoughts on “Show Custom Post Types on the Homepage

Leave a Reply

Your email address will not be published. Required fields are marked *