WordPress 基本自定义重写规则

发布于 2024-12-08 11:58:35 字数 544 浏览 0 评论 0原文

我对这个简单的问题感到抱歉,这个问题无疑已经在这个网站上被回答了无数次,但我不明白为什么我的重写规则没有生效。

这是我的代码:

add_action('init', 'update_rewrite_rules');
function update_rewrite_rules(){
    add_rewrite_rule('^org/([^/]+)', 'index.php?pagename=about-us&org=$matches[1]', 'top');
    add_rewrite_tag('%org%', '[0-9]+');
}

据我了解,这应该将“myurl.com/org/13”转换为“myurl.com/index.php?pagename=about-su&org=13”。我做错了什么???

我可以将其写入 .htaccess 文件中,但是,当然,我遇到了 WordPress 的自定义 PHP 重写函数取代我的代码的问题,因此只找到了变量,但找不到页面。

无论如何,任何建议或需要考虑的问题将不胜感激!谢谢。

I'm sorry for this straightforward question that has doubtless been answered countless times on this site, but I can't figure out why my rewrite rule is not taking effect.

Here's my code:

add_action('init', 'update_rewrite_rules');
function update_rewrite_rules(){
    add_rewrite_rule('^org/([^/]+)', 'index.php?pagename=about-us&org=$matches[1]', 'top');
    add_rewrite_tag('%org%', '[0-9]+');
}

As far as I understand it, this should convert "myurl.com/org/13" to "myurl.com/index.php?pagename=about-su&org=13". What am I doing wrong???

I can write it into the .htaccess file just fine, but, of course, I run into the issue of Wordpress' custom PHP rewrite function superseding my code, so only the variable is found, but not the page.

Anyway, any advice or questions to think about would be appreciated! Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海螺姑娘 2024-12-15 11:58:35

我相信您必须在实际重写规则之前注册查询变量。此外,正如 Wordpress Rewrite API 中所述,只有在新规则被刷新后,它才会识别它们缓存被重新生成。

//Ensure the $wp_rewrite global is loaded
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules();

请注意,出于性能原因,您不应在每个请求时都执行此操作,而应仅在插件激活时执行此操作。

add_action('admin_init', 'flush_rewrite_rules');

还有另一种添加自定义重写规则的方法,如自定义查询中所述。

I believe you have to register your query variable before the actual rewrite rule. Also, as stated in Wordpress Rewrite API, it will only recognize the new rules once they are flushed and the cache is regenerated.

//Ensure the $wp_rewrite global is loaded
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules();

Note that, for performance reasons, you should not do this every request, only on your plugin activation.

add_action('admin_init', 'flush_rewrite_rules');

There is also another way to add custom rewrite rules, as described in Custom Quesries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文