自定义文章类型的固定链接,默认情况下链接规则为 http://网站域名/文章类型/文章名称,如若要将其改为 http://网站域名/文章类型/分类名称/文章名称,在后台 “设置” – “固定链接” 中无法直接修改,所以需要使用代码进行修改。
1、创建自定义文章类型 document
register_post_type(
'document',
array(
'rewrite' => array('slug' => 'document/%contents%', 'with_front' => false),
'has_archive' => 'document',
// your other args...
)
);
2、为文章类型创建自定义分类 contents
register_taxonomy(
'contents',
'document',
array(
'rewrite' => array( 'slug' => 'contents', 'with_front' => false ),
// your other args...
)
);
3、向 post_type_link 添加一个过滤器
function mookwai_document_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'document' ){
$terms = wp_get_object_terms( $post->ID, 'contents' );
if( $terms ){
return str_replace( '%contents%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'mookwai_document_permalinks', 1, 2 );
4、后台更新固定链接
在后台 “设置” – “固定链接” 中重新更新一下即可。
参考链接:
https://wpsmith.net/2019/custom-rewrite-rules-custom-post-types-taxonomies/
https://jonchristopher.us/blog/revisiting-custom-post-types-taxonomies-permalinks-slugs/