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

时间:2017-11-21 11:31:29

标签: wordpress

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

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'和猫的#39;发布类型。因此,我创建了一个名为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并同时显示“狗”和“狗”。并且' cat'帖子。相反,虽然它确实显示了“狗”和“狗”。并且' cat'帖子,它不会提取archive-dog.php但会回到archive.php。如果我删除了“猫”。来自更改后的主要查询的帖子类型,只留下“狗”,一切正常。如何同时拥有两种帖子类型我的自定义存档模板?

1 个答案:

答案 0 :(得分:0)

将以下代码放在你的functions.php中并享受:

ng text -e <env-variable>
相关问题