在创建我喜欢的permalink结构时遇到一些问题。在Stack Exchange上找到一段代码,很遗憾,我现在找不到。
我有一个叫CPT的project
我希望能够实现这种结构https://mysite.tld/taxonomy/title-of-project
目前正在使用此代码
/* Initialize Project CPT **/
add_action( \'init\', function() {
$rewrite = array(
\'slug\' => \'%department%\',
\'with_front\' => true
);
$args = array(
\'label\' => __( \'Project\', \'sage\' ),
\'labels\' => $labels,
\'supports\' => array( \'title\', \'thumbnail\'),
\'hierarchical\' => false,
\'public\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'menu_position\' => 5,
\'show_in_admin_bar\' => false,
\'show_in_nav_menus\' => true,
\'can_export\' => true,
\'has_archive\' => false,
\'exclude_from_search\' => false,
\'publicly_queryable\' => true,
\'rewrite\' => $rewrite,
\'capability_type\' => \'post\',
\'show_in_rest\' => true,
);
register_post_type( \'project\', $args );
}, 0);
/* Department Taxonomy **/
add_action( \'init\', function () {
register_taxonomy(\'department\', array(\'project\'), array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'show_ui\' => true,
\'show_admin_column\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'with_front\' => false),
));
}, 0 );
/* Filter post_type_link to insert the taxonomy term into the permalink **/
add_filter(\'post_type_link\', function ( $post_link, $id = 0 ) {
$post = get_post($id);
if (is_object( $post ) && $post->post_type == \'project\' ) {
$terms = wp_get_object_terms( $post->ID, \'department\' );
if($terms) {
return str_replace( \'%department%\' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}, 1, 3);
但是,当添加此代码时,我的所有页面都将为404。如果我注释掉第4行:
//\'slug\' => \'%department%\',
那么它就可以正常工作了。我想这可能是一次永久性的碰撞,但我不知道该如何解决它。如果有人能给我指出正确的方向,我会非常高兴。