wordpress同时定义多个自定义文章类型的固定链接

WordPress教程 1615

前面分享的《wordpress同时创建多个自定义文章类型的方法》给需要创建多个自定义文章类型的用户带来了极大的方便,在创建了多个自定义文章类型后,一般会选择修改其默认的固定链接,博客吧也分享过自定义文章类型固定链接的修改方法,但是按照需要有多少个文章类型就添加多少次代码,显然不便于管理,而下面的方法把相关代码编写成函数,需要定义固定链接时,直接添加自定义文章类型名称即可。

把下面的代码添加至主题的functions.php文件第一行<?php下面:

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
29
$mytypes = array(//根据需要添加你的自定义文章类型
    'post_type1' => 'slug1',
    'post_type2' => 'slug2',    
    );
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'
            );
    }
}

上面代码中的'post_type1' => 'slug1''post_type2' => 'slug2'就是要定义的两个自定义文章类型,把post_type1post_type2修改为自己的自定义文章类型名称,slug1slug2修改自己的url中要显示的别名(用英文)。

精品推荐: