通用API文档

路由重写规则

💡 云策文档标注

概述

本文档介绍了 WordPress 中自定义重写规则的功能,允许主题和插件开发者通过编程方式添加新的 URL 重写规则。核心内容包括相关函数、Hook 和类,并强调了规则生效前需刷新固定链接。

关键要点

  • WordPress 提供函数如 add_rewrite_rule()、add_rewrite_tag() 和 add_rewrite_endpoint() 来创建自定义重写规则。
  • 自定义规则通常需要在 init hook 中调用,并需刷新固定链接(通过 flush_rules() 或 WP-Admin 设置)才能生效。
  • WP_Rewrite 类是内置的 URL 重写类,提供底层方法支持。
  • 多个 Filter Hook(如 rewrite_rules_array、post_rewrite_rules)可用于修改或扩展重写规则。
  • Action Hook generate_rewrite_rules 在所有规则创建后运行,便于执行后续操作。

代码示例

// 示例:添加自定义重写规则
add_action('init', 'my_custom_rewrite_rules');
function my_custom_rewrite_rules() {
    add_rewrite_rule('^my-page/([^/]*)/?', 'index.php?pagename=my-page&custom_var=$matches[1]', 'top');
    flush_rules(); // 一次性使用以生效
}

注意事项

  • 自定义重写规则需在 init hook 中注册,以确保正确加载。
  • 规则更改后,必须刷新固定链接(如访问 Settings -> Permalinks 或调用 flush_rules())才能生效,避免缓存问题。
  • 使用 flush_rules() 应谨慎,建议仅在开发或规则变更时调用,以避免性能开销。

📄 原文内容

Description

WordPress allows theme and plugin developers to programmatically specify new, custom rewrite rules.

The following functions (which are mostly aliases for WP_Rewrite methods) can be used to achieve this.

Please note that these rules are usually called inside the init hook. Furthermore, permalinks will need to be refreshed (you can do this from WP-Admin under Settings -> Permalinks) before the rewrite changes will take effect. Requires one-time use of flush_rules() to take effect.

API Reference

Articles

  • Class: WP_Rewrite – An overview of WordPress’s built-in URL rewrite class.

Hooks

Functions