自定义固定链接结构:/%custom-post-type%/%custom-taxonomy%/%post-name%/ [英] Custom permalink structure: /%custom-post-type%/%custom-taxonomy%/%post-name%/
问题描述
我正在尝试创建一个自定义永久链接结构,以便我完成以下操作.
I'm trying to create a custom permalink structure that will allow me to accomplish the following.
- 我有一个名为项目"的自定义帖子类型
- 我有一个名为project-category"的自定义分类法,它被分配给 CPTprojects"
我希望我的永久链接结构如下所示:
I want my permalink structure to look like this:
项目/类别/项目名称
或
/%custom-post-type%/%custom-taxonomy%/%post-name%/
/%custom-post-type%/%custom-taxonomy%/%post-name%/
我已经能够成功地将/%category%/用于普通的、现成的 WP 帖子的永久链接,但不能用于 CPT.
I've been able to succesfully use /%category%/ in permalinks for normal, out-of-the-box WP posts, but not for CPTs.
创建这样的永久链接结构将如何影响 URL 或其他页面?是否可以定义自定义永久链接结构并将其限制为单个 CPT?
How would creating such a permalink structure affect the URLs or other pages? Is it possible de define a custom permalink structure and restrict it to a single CPT?
谢谢
推荐答案
你很幸运,我只是不得不为一个客户项目做这件事.我使用 WordPress Stackexchange 上的这个答案 作为指南:
Lucky for you, I just had to do this for a client project. I used this answer on the WordPress Stackexchange as a guide:
/**
* Tell WordPress how to interpret our project URL structure
*
* @param array $rules Existing rewrite rules
* @return array
*/
function so23698827_add_rewrite_rules( $rules ) {
$new = array();
$new['projects/([^/]+)/(.+)/?$'] = 'index.php?cpt_project=$matches[2]';
$new['projects/(.+)/?$'] = 'index.php?cpt_project_category=$matches[1]';
return array_merge( $new, $rules ); // Ensure our rules come first
}
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );
/**
* Handle the '%project_category%' URL placeholder
*
* @param str $link The link to the post
* @param WP_Post object $post The post object
* @return str
*/
function so23698827_filter_post_type_link( $link, $post ) {
if ( $post->post_type == 'cpt_project' ) {
if ( $cats = get_the_terms( $post->ID, 'cpt_project_category' ) ) {
$link = str_replace( '%project_category%', current( $cats )->slug, $link );
}
}
return $link;
}
add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );
在注册自定义帖子类型和分类时,请务必使用以下设置:
When registering the custom post type and taxonomy, be sure to use the following settings:
// Used for registering cpt_project custom post type
$post_type_args = array(
'rewrite' => array(
'slug' => 'projects/%project_category%',
'with_front' => true
)
);
// Some of the args being passed to register_taxonomy() for 'cpt_project_category'
$taxonomy_args = array(
'rewrite' => array(
'slug' => 'projects',
'with_front' => true
)
);
当然,完成后一定要刷新重写规则.祝你好运!
Of course, be sure to flush rewrite rules when you're done. Good luck!
这篇关于自定义固定链接结构:/%custom-post-type%/%custom-taxonomy%/%post-name%/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!