WordPress post_link生成的自定义permalink无法访问问题求助
自定义分类文章Permalink修改后出现404错误
我写了这段代码用来给特定分类的文章修改永久链接:
/* 2024-12-04: Define custom permalinks for some specific posts */ function post_custom_permalink($permalink, $post) { // Check if post belongs to some specific categories if (has_category('case-studies', $post)) { $permalink = home_url('case-studies/' . $post->post_name . '/'); return $permalink; } else if (has_category('guides', $post)) { $permalink = home_url('guides/' . $post->post_name . '/'); return $permalink; } else if (has_category('tools', $post)) { $permalink = home_url('tools/' . $post->post_name . '/'); return $permalink; } // For all other cases, return the original permalink return $permalink; } add_filter('post_link', 'post_custom_permalink', 10, 2);
现在遇到的问题是:创建分类为tools的文章「Test Tool」时,显示的永久链接是https://www.sample.com/tools/test-tool/,但访问这个链接会出现404错误;反而访问https://www.sample.com/test-tool/能正常打开文章。这是为什么?
原因分析
你写的代码只修改了前端显示的链接文本,但没有给WordPress的路由系统添加对应的解析规则。WordPress默认的URL匹配规则里,没有/tools/文章别名/这种格式的处理逻辑,所以服务器无法识别这个路径对应的内容,返回404错误。而/test-tool/是文章默认的post-name格式链接,符合WordPress原生的路由规则,因此能正常访问。
解决方案
要让自定义Permalink正常工作,需要补充两步操作:
- 添加自定义重写规则,让WordPress能识别
/case-studies/xxx/、/guides/xxx/、/tools/xxx/这类URL,指向对应的文章。 - 刷新WordPress的重写规则(在固定链接设置页面保存一次即可)。
修改后的完整代码如下:
/* 2024-12-04: Define custom permalinks for some specific posts */ function post_custom_permalink($permalink, $post) { // Check if post belongs to some specific categories if (has_category('case-studies', $post)) { $permalink = home_url('case-studies/' . $post->post_name . '/'); return $permalink; } else if (has_category('guides', $post)) { $permalink = home_url('guides/' . $post->post_name . '/'); return $permalink; } else if (has_category('tools', $post)) { $permalink = home_url('tools/' . $post->post_name . '/'); return $permalink; } // For all other cases, return the original permalink return $permalink; } add_filter('post_link', 'post_custom_permalink', 10, 2); // 添加自定义重写规则 function custom_permalink_rewrite_rules() { // 匹配case-studies/xxx/格式的URL add_rewrite_rule( '^case-studies/([^/]+)/?$', 'index.php?name=$matches[1]', 'top' ); // 匹配guides/xxx/格式的URL add_rewrite_rule( '^guides/([^/]+)/?$', 'index.php?name=$matches[1]', 'top' ); // 匹配tools/xxx/格式的URL add_rewrite_rule( '^tools/([^/]+)/?$', 'index.php?name=$matches[1]', 'top' ); } add_action('init', 'custom_permalink_rewrite_rules');
关键操作提醒
代码添加完成后,必须进入WordPress后台的「设置」→「固定链接」页面,直接点击「保存更改」(无需修改任何设置),这一步会刷新WordPress的重写规则库,让新添加的规则生效。
内容的提问来源于stack exchange,提问作者alancc
相关产品推荐
相关产品推荐

