Setting a Custom Post Type Archive as the Home Page

It took me quite a bit of research to figure out how to modify the home page query to use a custom post type archive. Here’s what it takes…

1. Set the home page to display a static page

On the Settings > Reading page, make sure the “Your homepage displays” option is set to “A static page”. I don’t think the page itself really matters, since it will just get bypassed in our next step. I just created a blank page select as the home page to ensure it didn’t touch any of my existing pages (I don’t know if that’s necessary though).

2. Use pre_get_posts to load the custom post type archive

Here’s where things get interesting. There are a lot of methods that people are describing on various forums. However, most of them either involve custom theme templates or broken pagination. Here’s what worked for me:

function cpt_front_page( $wp_query ){

	// Ensure this filter isn't applied to the admin area
	if ( is_admin() ) {
		return;
	}

	// Run if the home page is set to a static page
	if ( $wp_query->get( 'page_id' ) == get_option( 'page_on_front' ) ){
		$wp_query->set( 'post_type', 'custom-post-type-slug' );
		$wp_query->set( 'page_id', '' ); //Empty

		// Set properties that describe the page to reflect that we aren't really displaying a static page
		$wp_query->is_page = 0;
		$wp_query->is_singular = 0;
		$wp_query->is_post_type_archive = 1;
		$wp_query->is_archive = 1;

		// Set pagination
		$paged = !empty( get_query_var( 'page') ) ? get_query_var( 'page' ) : 1;
		$wp_query->set( 'paged', $paged );
	}
}
add_action( 'pre_get_posts', 'cpt_front_page' );

Just change custom-post-type-slug to the slug/id of the relevant post type.

Credits:
https://wordpress.stackexchange.com/questions/30851/how-to-use-a-custom-post-type-archive-as-front-page
https://wordpress.stackexchange.com/questions/154462/pagination-doesnt-function-properly-for-archive-of-a-custom-post-type-set-as-th

 

Leave a Comment

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