我已经使用 WordPress 自己的函数设置了一个重写规则。 重写代码如下所示:
add_rewrite_rule('^testrule/(.+)?$', 'index.php?p=$matches[1]', 'top');
规则有效,只是每当我访问该 url 时,我都会被重定向,这使得 URL 发生变化,我不希望这种情况发生。
有什么建议吗?
最佳答案
你可能应该使用 add_permastruct和 add_rewrite_tag对我的情况有帮助的功能。虽然我的情况有点不同,但想法是相似的。
我有一个名为“guide”的自定义帖子类型,我需要它的自定义 URL(不同于自定义帖子名称),而且我在 URL 中使用了 post slugs,这是我的解决方案:
add_action('init', 'custom_permastruct_rewrite');
function custom_permastruct_rewrite() {
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag("%guide_slug%", '([^/]+)', "post_type=guide&name=");
$wp_rewrite->add_permastruct('my_rule', '/my_custom_name/%guide_slug%', false);
}
所以当你去地址时: http://example.com/my_custom_name/my_post_slug 在上面的 URL 下,它显示的内容来自: http://example.com/?post_type=guide&name=my_post_slug (不重定向到最后一个地址)
您可以根据您的需要调整“post_type=guide&name=”,例如您可以通过 id 查找帖子 - 因此将“p=”放在那里将显示来自:http://example.com/my_custom_name/24 的内容至 http://example.com/?p=24
关于php - 使用wordpress重写url时如何避免重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13858448/