【发布时间】:2017-11-21 11:31:28
【问题描述】:
我已经注册了以下两种自定义帖子类型:
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 );
}
在“狗”帖子类型 (mysite.com/dog) 的存档页面中,我想显示同时使用“狗”和“猫”帖子类型的帖子。所以我创建了一个名为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 并显示“狗”和“猫”的帖子。相反,虽然它确实显示了“狗”和“猫”的帖子,但它并没有选择archive-dog.php,而是回退到archive.php。如果我从更改后的主查询中删除“猫”帖子类型,只留下“狗”,一切正常。我怎样才能同时拥有两种帖子类型和我的自定义存档模板?
【问题讨论】:
-
我不认为archive-dog.php与更改的查询有任何关系,尝试更新一次永久链接,它可能正常工作,未经测试,只是一个假设。
标签: wordpress