Wordpress后端中的permalink配置仅适用于标准帖子和页面。对于CPT,默认URL结构为http://example.com/cpt-identifier/post-slug
. 如果您想要为您的CPT提供不同的URL结构,那么您必须定义并注册自己的重写规则。
例如:
add_action( \'init\', \'register_posttype\' );
function register_posttype() {
register_post_type( \'my_cpt\', //this will be in the URL as CPT identifier
array(
\'labels\' => array(
\'name\' => __( \'My Custom Post Types\' ),
\'singular_name\' => __( \'Custom Post Type\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'products\'), //This will override the CPT identifier
)
);
}
如果您想在CPT的URL结构中包括dinamic标记,如year,则必须定义自己的重写规则和永久链接过滤器:
add_action( \'init\', \'register_posttype\' );
function register_posttype() {
register_post_type( \'my_cpt\', //this will be in the URL as CPT identifier
array(
\'labels\' => array(
\'name\' => __( \'My Custom Post Types\' ),
\'singular_name\' => __( \'Custom Post Type\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'%year%/my_cpt\'), //This will override the CPT identifier
)
);
}
add_filter(\'post_type_link\', \'modify_permalink\');
function modify_permalink($url, $post = null) {
// limit to certain post type. remove if not needed
if (get_post_type($post) != \'my_cpt\') {
return $url;
} elseif(!is_object($post)) {
global $post;
}
$url = str_replace("%year%", get_the_date(\'Y\'), $url);
return $url;
}
add_action(\'init\',\'my_add_rewrite_rules\');
function my_add_rewrite_rules() {
add_rewrite_rule(\'([0-9])/my_cpt/(.+)/?$\', \'index.php?post_type=my_cpt&post=$matches[1]\', \'top\' );
}