关于自定义文章类型和固定链接结构,大家可以想回顾一下:
自定义文章类型默认输入的固定链接结构为 /%postname% 。假设我们添加的自定义文章类型为 book ,那么默认输出的 book 文章链接一般为 http://域名/book/slug (slug为标题别名)。如果文章标题是中文(比如:一本好书),而且你没有手动或者使用插件翻译为非中文的 slug (a-nice-book),那么显示的链接就会是http://域名/book/一本好书 ,这样一来,文章链接的中文部分就会显示成乱码,实在不符合我们的审美标准了。
那么,我们可以将 /%postname% 改为 /%post_id% 或 /%post_id%.html 样式,使用ID来显示。要实现这个目的,可以使用文章开头提到的 Custom Post Type Permalinks 插件。如果你是插件或主题开发者,一般都喜欢直接通过代码定义好默认的固定链接结构。
可以在插件函数文件或主题的functions.php 文件添加下面的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 设置 book 这种自定义文章类型的固定链接结构为 ID.html
* http://www.wpdaxue.com/custom-post-type-permalink-code.html
*/
add_filter( 'post_type_link' , 'custom_book_link' , 1 , 3 ) ;
function custom_book_link( $link , $post = 0 ) {
if ( $post -> post_type == 'book' ) {
return home_url( 'book/' . $post -> ID . '.html' ) ;
} else {
return $link ;
}
}
add_action( 'init' , 'custom_book_rewrites_init' ) ;
function custom_book_rewrites_init( ) {
add_rewrite_rule(
'book/([0-9]+)?.html$' ,
'index.php?post_type=book&p=$matches[1]' ,
'top' ) ;
}
以上代码就可以输出形如 /book/123.html 的链接。请将代码中所有 book 替换为你的自定义文章类型。
如果你要同时定义多种自定义文章类型,可以使用下面的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 设置多种自定义文章类型的固定链接结构为 ID.html
* http://www.wpdaxue.com/custom-post-type-permalink-code.html
*/
$mytypes = array ( //根据需要添加你的自定义文章类型
'type1' => 'slug1' ,
'type2' => 'slug2' ,
'type3' => 'slug3'
) ;
add_filter( 'post_type_link' , 'my_custom_post_type_link' , 1 , 3 ) ;
function my_custom_post_type_link( $link , $post = 0 ) {
global $mytypes ;
if ( in_array ( $post -> post_type , array_keys ( $mytypes ) ) ) {
return home_url( $mytypes [ $post -> post_type ] . '/' . $post -> ID . '.html' ) ;
} else {
return $link ;
}
}
add_action( 'init' , 'my_custom_post_type_rewrites_init' ) ;
function my_custom_post_type_rewrites_init( ) {
global $mytypes ;
foreach ( $mytypes as $k => $v ) {
add_rewrite_rule(
$v . '/([0-9]+)?.html$' ,
'index.php?post_type=' . $k . '&p=$matches[1]' ,
'top' ) ;
}
}
参考资料:http://www.solagirl.net/custom-post-type-permalink.html