Skip to content

Instantly share code, notes, and snippets.

@blainerobison
Created January 22, 2016 00:04
Show Gist options
  • Save blainerobison/1c41ffdc55c0c27455f7 to your computer and use it in GitHub Desktop.
Save blainerobison/1c41ffdc55c0c27455f7 to your computer and use it in GitHub Desktop.
Use specific template when multiple post types defined via pre_get_posts hook.
<?php
/**
* Modify Main Query
*
* Add multiple post types to main query.
*
* @param object $query main query object
* @return no return value necessary.
*/
function _s_post_type_1_archive( $query ) {
if ( ! is_post_type_archive( 'post_type_1' ) || is_admin() || ! $query->is_main_query() )
return;
$query->set( 'post_type', array( 'post_type_1', 'post_type_2' ) );
}
add_action( 'pre_get_posts', '_s_post_type_1_archive' );
/**
* Force Use of Template
*
* It's not clear to WordPress which template to use when querying multiple
* post types. This check forces the use of a specific template
*
* @return void
*/
function _s_redirect_template( $template ) {
// cast as an array when there's only a single post type
$post_types = (array) get_query_var( 'post_type_1' );
// check for both resource and faq as post types
if ( in_array( 'post_type_1', $post_types ) && in_array( 'post_type_2', $post_types ) ) :
$new_template = locate_template( array( 'archive-post_type_1.php' ) );
if ( '' != $new_template )
return $new_template;
endif;
return $template;
}
add_action( 'template_include', '_s_redirect_template' );
@bigbritches
Copy link

This is really old, but it's just helped me out tremendously, and I wanted to point out one tiny error:

$post_types = (array) get_query_var( 'post_type_1' );

should be:

$post_types = (array) get_query_var( 'post_type' );

Thanks for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment