本文档介绍了 WordPress 中自定义重写规则的功能,允许主题和插件开发者通过编程方式添加新的 URL 重写规则。核心内容包括相关函数、Hook 和类,并强调了规则生效前需刷新固定链接。
// 示例:添加自定义重写规则
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(); // 一次性使用以生效
}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.
WP_Rewrite – An overview of WordPress’s built-in URL rewrite class.root_rewrite_rules – Filters the rewrite rules generated for the root of your weblog.post_rewrite_rules – Filters the rewrite rules generated for permalink URLs.page_rewrite_rules – Filters the rewrite rules generated for your Pages.date_rewrite_rules – Filters the rewrite rules generated for dated archive URLs.search_rewrite_rules – Filters the rewrite rules generated for search URLs.comments_rewrite_rules – Filters the rewrite rules generated for the latest comment feed URLs.author_rewrite_rules – Filters the rewrite rules generated for author archive URLs.rewrite_rules_array – Filters all the rewrite rules at once.{$permastructname}_rewrite_rules – Can be used to create or modify rewrite rules for any custom permastructs, such as taxonomies or custom post types.generate_rewrite_rules – Runs after all the rules have been created.add_rewrite_tag() – Can be used to allow WordPress to recognize custom variables (particularly custom querystring variables).add_rewrite_rule() – Allows you to specify new, custom rewrite rules.add_rewrite_endpoint() – Add a new endpoint like /trackback/flush_rules() – Regenerate the rewrite rules and save them to the database.flush_rewrite_rules() – Remove rewrite rules and then recreate rewrite rules.generate_rewrite_rules() – Generates rewrite rules from a permalink structureadd_permastruct() – Add a new permastructadd_feed()– Add a new feed type like /atom1/