我有一个带有层次分类法的自定义帖子类型。permalink结构如下:
www.mysite.com/post_type/taxonomy_term -> works (tax archive page)
www.mysite.com/post_type/taxonomy_term/post_name -> works (post page)
www.mysite.com/post_type/taxonomy_term/taxonomy_sub_term -> 404 error (sub tax archive page)
www.mysite.com/post_type/taxonomy_term/taxonomy_sub_term/post_name -> works (post page)
具有重要设置的自定义post类型函数(从CPT UI输出):
$args = array(
"has_archive" => true,
"hierarchical" => false,
"rewrite" => array(
"slug" => "diensten",
"with_front" => false
),
"taxonomies" => array( "dienst_categorie" ),
);
register_post_type( "diensten", $args );
具有重要设置的分类功能(从CPT UI输出):
$args = array(
"hierarchical" => true,
"rewrite" => array(
\'slug\' => \'diensten\',
\'with_front\' => false,
\'hierarchical\' => true,
),
);
register_taxonomy( "dienst_categorie", array( "diensten" ), $args );
使用一些基于
this website 我得到了以下代码:
function resources_cpt_generating_rule( $wp_rewrite ) {
$rules = array();
$post_type_diensten = \'diensten\';
$terms_diensten = get_terms( array(
\'taxonomy\' => \'dienst_categorie\',
\'hide_empty\' => false,
) );
foreach ( $terms_diensten as $term ) {
if ( $term->parent > 0 ) {
$pterm = get_term( $term->parent, \'dienst_categorie\' );
// The line below doesn\'t work as expected.
$rules[ \'diensten/\' . $pterm->slug . \'/\' . $term->slug . \'/?$\' ] = \'index.php?taxonomy=dienst_categorie&term=\' . $term->slug;
$rules[ \'diensten/\' . $pterm->slug . \'/\' . $term->slug . \'/([^(/)]*)$\' ] = \'index.php?post_type=\' . $$post_type_diensten . \'&\' . $post_type_diensten . \'=$matches[1]&name=$matches[1]\';
} else {
$rules[ \'diensten/\' . $term->slug . \'/([^/]*)$\' ] = \'index.php?post_type=\' . $post_type_diensten . \'&\' . $post_type_diensten . \'=$matches[1]&name=$matches[1]\';
}
// This line works, but is not dynamic.
$rules[ \'diensten/zonwering/zonweringreparaties/?$\' ] = \'index.php?taxonomy=dienst_categorie&term=zonweringreparaties\';
}
}
add_filter( \'generate_rewrite_rules\', \'resources_cpt_generating_rule\' );
function change_link( $permalink, $post ) {
if ( \'diensten\' === $post->post_type ) {
$resource_terms = get_the_terms( $post, \'dienst_categorie\' );
if ( ! empty( $resource_terms ) ) {
foreach ( $resource_terms as $term ) {
if ( \'featured\' === $term->slug ) {
continue;
}
if ( $term->parent > 0 ) {
$pterm = get_term( $term->parent );
$permalink = get_home_url() . \'/diensten/\' . $pterm->slug . \'/\' . $term->slug . \'/\' . $post->post_name;
} else {
$permalink = get_home_url() . \'/diensten/\' . $term->slug . \'/\' . $post->post_name;
}
break;
}
}
return $permalink;
}
}
add_filter( \'post_type_link\', \'change_link\', 10, 2 );
请注意注释的行。一个是硬编码的,另一个是动态的,并且基于模板中的测试,动态的一个输出与硬编码的相同的代码,但它不起作用。我怀疑这与regex模式有关,但我不知道为什么。
我的问题是:要根据术语/子术语url层次结构访问子术语的归档页面,正确的重写规则是什么?