在寻找解决方案时,我得到了以下帖子:Taxonomies with same slug as CPT
因此,基本上您需要添加自定义重写规则,我还没有测试解决方案,但我想它会适合您。
/* Register CPT
*/
function wpse_138987_post_type_filter() {
register_post_type(\'filter\', array(
\'labels\' => array(
\'name\' => \'Filter\',
\'all_items\' => \'All Posts\'
),
\'public\' => true
));
}
add_action(\'init\', \'wpse_138987_post_type_filter\');
// register taxonomy
function wpse_138987_taxonomy_service() {
register_taxonomy(\'service\', array(\'filter\'), array(
\'labels\' => array(
\'name\' => \'Service\'
),
\'hierarchical\' => true,
\'public\' => true,
\'show_ui\' => true,
\'show_admin_column\' => true,
\'show_in_nav_menus\' => true,
\'show_tagcloud\' => true,
\'rewrite\' => array(\'slug\' => \'filter\')
));
}
add_action(\'init\', \'wpse_138987_taxonomy_service\');
/*
* Replace Taxonomy slug with Post Type slug in url
*/
function taxonomy_slug_rewrite($wp_rewrite) {
$rules = array();
// get all custom taxonomies
$taxonomies = get_taxonomies(array(\'_builtin\' => false), \'objects\');
// get all custom post types
$post_types = get_post_types(array(\'public\' => true, \'_builtin\' => false), \'objects\');
foreach ($post_types as $post_type) {
foreach ($taxonomies as $taxonomy) {
// go through all post types which this taxonomy is assigned to
foreach ($taxonomy->object_type as $object_type) {
// check if taxonomy is registered for this custom type
if ($object_type == $post_type->rewrite[\'slug\']) {
// get category objects
$terms = get_categories(array(\'type\' => $object_type, \'taxonomy\' => $taxonomy->name, \'hide_empty\' => 0));
// make rules
foreach ($terms as $term) {
$rules[$object_type . \'/\' . $term->slug . \'/?$\'] = \'index.php?\' . $term->taxonomy . \'=\' . $term->slug;
}
}
}
}
}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter(\'generate_rewrite_rules\', \'taxonomy_slug_rewrite\');
上述解决方案仅在您使用带有Post name的Permalinks时有效。
确保在添加代码后保存permalink,以刷新重写规则。
此外,您还需要为自定义帖子类型存档和分类添加文件:
archive-filter.php
single-filter.php
taxonomy-service.php
转到设置/永久链接,并使用结构/%postname%/保存更改。