我正在尝试修改默认帖子类型的permalink结构post
包括自定义分类术语。以下是我的函数和过滤器:
/**
* Add media type slug to URL structure for posts
*/
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
$media_type = get_taxonomy_parents( $first_term, \'media-type\', false, \'/\', true );
// Remove trailing slash
$media_type = trim( $media_type, \'/\' );
} else {
$media_type = \'articles\';
}
$media_type = urlencode($media_type);
$media_type = str_replace( \'%2F\', \'/\' , $media_type );
$link = str_replace( \'%media_type%\', $media_type , $link );
return $link;
}
在中Settings > Permalinks
我正在使用的自定义结构/insights/%media_type%/%postname%/
.重置永久链接后,帖子URL的格式正确,但当我导航到该链接时,会看到404页。悲伤的熊猫。
我是如何成为一个哑巴的,我应该如何变得更聪明才能做到这一点?
EDIT: 读了一点法典后,我意识到我忘了添加重写规则。也就是说,我仍然缺少一些东西。我稍微更新了上面的函数hierarchical
到true
在rewrite
属性。现在,我的帖子工作正常,除非它们被分配给层次结构中的多个分类术语(例如,xx.com/insights/parent/post
有效,但xx.com/insights/parent/child/post
还是给了我一个404)。我的正则表达式技能很弱,所以想知道我是否遗漏了一些可以解释层次结构的东西。
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]&name=$matches[2]\',\'top\' );
}