WordPress为自定义帖子类型存档页面挑选了错误的模板

时间:2017-11-21 作者:grazianodev

我已注册了以下两种自定义帖子类型:

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 );
} 
在“dog”帖子类型的存档页面中(mysite.com/dog), 我想显示同时使用“dog”和“cat”帖子类型的帖子。因此,我创建了一个名为archive-dog.php 并将主查询更改为:

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\' ) ); 
        } 
    }         
}
当我访问时mysite.com/dog, 我希望Wordpress能自动接收archive-dog.php 并同时显示“dog”(狗)和“cat”(猫)贴子。相反,虽然它同时显示“dog”和“cat”帖子,但它不会拾取archive-dog.php 但又回到了archive.php. 如果我从修改后的主查询中删除“cat”post类型,只留下“dog”,那么一切都很好。如何同时拥有帖子类型和自定义存档模板?

1 个回复
最合适的回答,由SO网友:Welcher 整理而成

您可以通过template_include

add_filter( \'template_include\', \'cats_and_dogs_living_together\', 99 );

function cats_and_dogs_living_together( $template ) {

    if ( is_post_type_archive( array ( \'cat\', \'dog\' ) ) ) {
        $new_template = locate_template( array( \'archive-dog.php\' ) );
        if ( \'\' != $new_template ) {
            return $new_template;
        }
    }
    return $template;
}
希望这有帮助!

结束

相关推荐