我找到了一个解决方案,虽然我不相信这是最简单或最有效的解决方案,但它确实起到了作用。如果有人有一天对此感兴趣,并有了一个更干净的方法,我很乐意重新审视它。现在,以下是有效的方法:
在我的register_taxonomy
函数,将重写设置为:
\'rewrite\' => array(
\'slug\' => \'media-type\',
\'hierarchical\' => true,
),
然后,为帖子设置重写规则:
add_action( \'init\', \'xx_media_type_rewrite_tag\', 10, 0 );
function xx_media_type_rewrite_tag() {
add_rewrite_tag( \'%media_type%\', \'([^&]+)\', \'media-type=\' );
add_rewrite_rule( \'^insights/([^/]*)/([^/]*)/([^/]*)/?\',\'index.php?media_type=$matches[1]&media_type=$matches[2]&name=$matches[3]\',\'top\' );
add_rewrite_rule( \'^insights/([^/]*)/([^/]*)/?\',\'index.php?media_type=$matches[1]&name=$matches[2]\',\'top\' );
}
然后,过滤帖子链接(如果我知道自己在做什么,我会想象这部分看起来会更干净):
add_filter( \'post_link\', \'xx_filter_post_type_link\', 10, 2 );
function xx_filter_post_type_link( $link, $post ) {
if ( false === strpos( $link, \'%media_type%\') )
return $link;
$terms = wp_get_post_terms( $post->ID, \'media-type\');
// set media type; if none is found, provide a default value.
if ( 0 < count($terms) ) {
// Get first term in array
$first_term = $terms[0]->term_id;
// Create a string to represent hierarchy of terms
// get_taxonomy_parents() is a custom function that returns a string formatted as `$tax_parent . $separator . $tax_child . $separator` etc.
$media_type = get_taxonomy_parents( $first_term, \'media-type\', false, \'/\', true );
// Remove everything after second `/` character (we only want to go two levels deep into the tax hierarchy)
if ( 2 < substr_count( $media_type, \'/\' ) ) {
$media_type = substr( $media_type, 0, strpos( $media_type, \'/\', strpos( $media_type, \'/\') + 1 ) );
}
// Remove trailing slash
$media_type = trim( $media_type, \'/\' );
} else {
// Set default
$media_type = \'articles\';
}
// Encode for URL usage, but preserve slashes
$media_type = str_replace( \'%2F\', \'/\' , urlencode($media_type) );
$link = str_replace( \'%media_type%\', $media_type , $link );
return $link;
}