是的,这是可能的。我的问题有一部分得到了回答here 我会在这里输入完整的代码。
我有一个更大的函数,用于检查post taxanomy(在这种情况下,自定义post type的自定义类别)。然后我们检查是否存在特定的分类法,并更改URL结构。
add_filter(\'post_type_link\', \'replace_link\', 1, 3);
function replace_link( $link, $post = 0 ){
//custom post type "item"
if ( $post->post_type == \'item\' ){
//registered taxonomy for custom post type "item_category"
$terms = get_the_terms( $post->ID, \'item_category\' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
//put all taxanomy asigned to that post into one array
foreach ( $terms as $term )
{
$links[] = $term->name;
}
$links = str_replace(\' \', \'-\', $links);
endif;
//check if there is particular taxonomy and change URL structure
if (in_array("Food", $links)) {
return home_url(\'food/\'. $post->post_name);
}
if (in_array("Sport", $links)) {
return home_url(\'sport/\'. $post->post_name);
}
} else {
return $link;
}
}
现在有2个函数,因为我们需要相应的重写规则来为这些请求设置适当的查询变量。如果没有这些功能,我们将得到404页。
function custom_rewrite_rule1() {
add_rewrite_rule(\'food/([^/]+)/?$\',\'index.php?item=$matches[1]\',\'top\');
}
add_action(\'init\', \'custom_rewrite_rule1\', 10, 0);
function custom_rewrite_rule2() {
add_rewrite_rule(\'sport/([^/]+)/?$\',\'index.php?item=$matches[1]\',\'top\');
}
add_action(\'init\', \'custom_rewrite_rule2\', 10, 0);