grazdev
grazdev

Reputation: 1272

Wordpress Picks Up Wrong Template for Custom Post Type Archive Page

I have registered the two following custom post types:

function dogs() {

    $labels = array(
        'name' => 'Dogs'
    );

    $args = array(
        'labels' => $labels, 
        'public' => true,
        'has_archive' => true,            
        'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' )
    );

    register_post_type( 'dog', $args );
}

function cats() {

    $labels = array(
        'name' => 'Cats'
    );

    $args = array(
        'labels' => $labels, 
        'public' => true,
        'has_archive' => true,
        'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' )
    );

    register_post_type( 'cat', $args );
} 

In the archive page for the 'dog' post type (mysite.com/dog), I want to display posts that use both the 'dog' and the 'cat' post type. So I've created a custom template called archive-dog.php and altered the main query like this:

add_action( 'pre_get_posts', 'cats_and_dogs' ) );

function cats_and_dogs( $query ) {
    if( ! is_admin() && is_post_type_archive( 'dog' ) ) {
        if( $query->is_main_query() ) {  
            $query->set( 'post_type', array( 'dog', 'cat'  ) );
            $query->set( 'posts_per_page', 4 );
            $query->set( 'post_status', 'publish' );  
            $query->set( 'post__not_in', get_option( 'sticky_posts' ) ); 
        } 
    }         
}

When I visit mysite.com/dog, I would expect Wordpress to automatically pick up archive-dog.php and display both 'dog' and 'cat' posts. Instead, while it does display both 'dog' and 'cat' posts, it does not pick up the archive-dog.php but falls back to archive.php. If I remove the 'cat' post type from the altered main query and only leave 'dog', everything works fine. How can I have both both post types and my custom archive template?

Upvotes: 0

Views: 742

Answers (1)

Rajkumar Gour
Rajkumar Gour

Reputation: 1159

Place the below code in your functions.php and enjoy:

add_filter( 'template_include', 'use_archive_dog', 99 );
function use_archive_dog( $template ) {

    if ( is_post_type_archive('dog')  ) {
        $new_template = locate_template( array( 'archive-dog.php' ) );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }

    return $template;
}

Upvotes: 1

Related Questions