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
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. 🙂Thanks for pointing that out Danny! I’ve updated the code in the post and the gist to reflect that change.