如何通过模板及代码修改自定义文章类型、文章与页面固定链接?
嘿,正好之前折腾过WordPress各种固定链接的修改,给你一步步讲清楚怎么搞定自定义文章类型、博客文章和页面的URL调整:
1. 自定义文章类型(CPT)的固定链接修改
你提到的add_permastruct确实是核心方法,我通常会两种方式用它:
方式一:单独注册固定结构
如果你的CPT已经注册好了,单独加一段代码调整链接:
add_action('init', 'custom_cpt_permastruct'); function custom_cpt_permastruct() { // 比如给名为"book"的CPT设置链接为 /library/%book%/ add_permastruct('book', 'library/%book%', array( 'with_front' => false, // 不继承后台设置的主链接前缀(比如默认的"/blog/") 'ep_mask' => EP_PERMALINK, // 启用permalink端点支持 )); }
方式二:注册CPT时直接配置
更高效的方式是在register_post_type里直接设置rewrite参数,一步到位:
register_post_type('book', array( 'labels' => array(/* 你的标签设置 */), 'public' => true, 'has_archive' => true, // 重点在这里 'rewrite' => array( 'slug' => 'library', // 链接前缀 'with_front' => false, 'feeds' => true, // 启用feed链接 ), ));
2. 博客文章(Post类型)的固定链接修改
确实,add_permastruct对默认的post和page类型不生效,这时候得用过滤器来拦截链接生成逻辑:
修改单篇文章链接
用post_link过滤器自定义单篇博客文章的URL:
add_filter('post_link', 'custom_post_permalink', 10, 3); function custom_post_permalink($permalink, $post, $leavename) { // 只处理post类型,其他类型原样返回 if ($post->post_type !== 'post') { return $permalink; } // 自定义链接结构,比如改成 /journal/%postname%/ $custom_url = '/journal/' . $post->post_name . '/'; return home_url(user_trailingslashit($custom_url)); }
配套修改分类/标签归档链接
如果博客文章的前缀改了,归档链接也得同步调整,不然会不一致:
add_filter('term_link', 'custom_post_term_permalink', 10, 3); function custom_post_term_permalink($termlink, $term, $taxonomy) { // 只处理博客的分类和标签 if (!in_array($taxonomy, array('category', 'post_tag'))) { return $termlink; } // 替换默认的分类/标签前缀为自定义的 $termlink = str_replace( get_option('category_base') ? '/' . get_option('category_base') : '/category', '/journal/category', $termlink ); $termlink = str_replace( get_option('tag_base') ? '/' . get_option('tag_base') : '/tag', '/journal/tag', $termlink ); return $termlink; }
3. 页面(Page类型)的固定链接修改
和博客文章类似,用page_link过滤器来调整页面URL,还能处理子页面的层级:
add_filter('page_link', 'custom_page_permalink', 10, 2); function custom_page_permalink($permalink, $post_id) { $post = get_post($post_id); if ($post->post_type !== 'page') { return $permalink; } // 基础自定义前缀 $base = '/pages/'; $custom_url = $base . $post->post_name . '/'; // 处理子页面,保留父页面的slug层级 if ($post->post_parent) { $parent_post = get_post($post->post_parent); $custom_url = $base . $parent_post->post_name . '/' . $post->post_name . '/'; // 如果是多层子页面,可以写个递归函数来拼接所有父级slug,这里简化处理一级子页面 } return home_url(user_trailingslashit($custom_url)); }
关键注意事项
不管改哪种链接,一定要去后台「设置→固定链接」页面点击保存按钮,这会刷新WordPress的rewrite规则,不然新的链接会直接返回404。
另外,如果你的自定义前缀和其他CPT或默认路由冲突,可能会导致页面跳转错误,记得测试所有链接的访问情况。
内容的提问来源于stack exchange,提问作者roest
相关产品推荐
相关产品推荐

