This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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' );

https://gist.github.com/woodent/2068729

About

A professional WordPress developer for over a decade, Micah has worked on sites for Fortune 100 companies, has released over a dozen WordPress plugins, is a frequent speaker at WordCamps, co-organizes the WordPress Gwinnett meetup, is a co-host on the WP Square One podcast and shares his knowledge by blogging on WordPress development topics. Currently, Micah works at Bluehost as a WordPress contributor.

2 thoughts on “Show Custom Post Types on the Homepage

  1. Great snippet Micah, thanks. I would optimize the snippet by moving the get_post_types() call inside the conditional statement though. Saves a SQL query for every page request. 🙂

Leave a Reply

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

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