Boke112 导航的博客目录就是用 WordPress 的自定义文章类型来实现(PS:如果前期早点明白,将不会用自定义文章类型,而是直接用默认的文章类型类建立不同的分类实现),至于 WordPress 自定义文章类型的固定链接设置问题,上一次已经分享过用插件实现,具体请移步《自定义文章类型固定链接设置插件:Custom Post Type Permalinks》,今天分享的是纯代码实现。
我们用过 WordPress 自定义文章类型的都知道,自定义文章类型默认的固定链接结构为/%postname%。假设我们添加的自定义文章类型为 bulletin ,那么默认输出的 bulletin 文章链接一般为 http://域名/bulletin/ slug(slug 为标题别名)。如果文章标题是中文(比如:懿古今),而且你没有手动或者使用插件翻译为非中文的 slug (yigujin),那么显示的链接就会是 http://域名/ bulletin /懿古今 。这样一来,文章链接的中文部分就会显示成乱码,实在不符合我们的审美标准了。
那么,我们可以将/%postname%改为/%post_id%或 /%post_id%.html 样式,使用文章 ID 来显示。要实现这个目的,可以使用文章开头提到的 Custom Post Type Permalinks 插件。如果你天生不喜欢插件,我们还可以通过代码定义好默认的固定链接结构。
具体实现办法如下:
一、只有一个自定义文章类型的情况
1、直接将以下代码添加到主题的 functions.php 文件最后一个?>前面。
- /**
- * 设置 book 这种自定义文章类型的固定链接结构为 ID.html
- * https://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’ );
- add_rewrite_rule(
- ‘book/([0-9]+)?.html/comment-page-([0-9]{1,})$’,
- ‘index.php?post_type=book&p=$matches[1]&cpage=$matches[2]’,
- ‘top’
- );
- }
2、将以上代码中的 book 全部改为自己设置的自定义文章类型(如 bkml),即可实现 WordPress 自定义文章类型的固定链接为 http://域名/ bkml / ID.html。
温馨提示:以上代码中的 book/可以去掉变成 http://域名/ ID.html 这样的链接结构,也可以更改 book/为 a/,那么固定链接 http://域名/ book/ ID.html 也将会改为 http://域名/ a/ ID.html,而自定义文章类型没有变化。还有最后一点,在更改后记得在后台点击一次“设置”》“固定链接”,要不然会出现 404 错误哦。
二、有多个自定义文章类型的情况
方法是一样的,只需要将以下代码添加到主题的 functions.php 文件最后一个?>前面。
- /**
- * 设置多种自定义文章类型的固定链接结构为 ID.html
- * https://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’
- );
- add_rewrite_rule(
- $v.’/([0-9]+)?.html/comment-page-([0-9]{1,})$’,
- ‘index.php?post_type=’.$k.’&p=$matches[1]&cpage=$matches[2]’,
- ‘top’
- );
- }
- }
其中代码中的 type1、type2、type3 就是我们的自定义文章类型,slug1、slug2、slug3 就是自定义文章类型固定链接的类型地址。如 type1 改为 book,那么 slug1 可以改为 bkml,链接结构就是 http://域名/ bkml/ ID.html;也可以改为 a,链接地址就是 http://域名/ a/ ID.html。
文中技术及代码来源自WordPress 大学