Custom Post Type 链接使用别名加 .html 格式

LMS
1.5K+ 24

建立伪静态规则

建立 post-type/post-name.html 链接格式的伪静态规则,下面的代码是为所有 Custom Post Type 设置通用的链接格式伪静态规则,如果要对指定的 Post Type 设置单独的链接格式,则替换代码里 foreach 为指定 Post Type 名称即可。

add_action( 'rewrite_rules_array', 'rewrite_rules' );
function rewrite_rules( $rules ) {
    $new_rules = array();
    foreach ( get_post_types() as $t )
        $new_rules[ $t . '/([^/]+)\.html$' ] = 'index.php?post_type=' . $t . '&name=$matches[1]';
    return $new_rules + $rules;
}

格式化 Post Type 文章地址

格式化所有 Post Type 文章的默认地址,如果只是特定 Post Type 的则 用指定的 Post Type 名称替换即可。

add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link)
function custom_post_permalink ( $post_link ) {
    global $post;
    $type = get_post_type( $post->ID );
    return home_url( $type . '/' . $post->post_name . '.html' );
}

其他工作

add_filter( 'redirect_canonical', '__return_false' );

后台刷新固定链接设置。

文章转自:stackexchange.com

文章目录
THE END

评论 24

  1. 貌似后台配置完只要服务器有写权限,就能自动更新.htaccess,就可以用了吧

      1. 自定义结构里面输入/%category%/%postname%.html就是你现在的效果

  2. 咱这个主题也能用那个“让页面也带html后缀”的功能,但是那样以来对“下载”页面就无效了,你不试试折腾一下? :mrgreen:

    1. 我基本都没让页面带html后缀啊,有需要么?

      1. 我在知更鸟那看到的那个功能介绍,试了下,发现就下载页面不能用,没搞定,就退回去了。说不好页面带后缀好不好,可有可无吧。

        1. 对我这种分类链接去掉category的,给页面加个.html其实不错。

          1. 我那有一次去掉category后,网站直接错误了,不知道咋回事,太危险了。。。

            1. 是那个主题的问题,那个主题我也试过,是会出错。

              1. 果然,唉,真是苦逼了,喜欢上这么个主题……

                  1. 我是说我自己那。
                    bug的主题的cms部分里?

                    1. 好像是代码复制太多了冲突。

                      Windows 10
                  2. 其实,主题作者确实是牛逼的,可能后来功能集成得太多,hold不住了 :arrow:

  3. 你们在聊的神马?完全不懂……

    1. 折腾很久了,原来百度到的都不行,后来有个还算可行的又不是这种链接格式,自己修改的时候伪静态那个name一直没用对,搞不定,现在总算搞定了。

发表评论

Submit