I am starting to run into situations on projects where I am combining multiple plugins which all use add_rewrite_rule
and flush_rewrite_rules
at different points. As we all know, calling flush_rewrite_rules
on every page load is a bad thing.
The problem arises when Plugin A has not yet added it’s rewrite rules, but Plugin B calls flush_rewrite_rules
. Plugin A is a good citizen, and doesn’t call flush_rewrite_rules
unless it needs to and so now it’s rewrite rules are no longer present.
I’ve been looking for an action which gets called before the rules are collated by flush_rewrite_rules
, which I can hook for my add_rewrite_rule
calls to be sure all rules are present before they are compiled, but I’ve not found one. Any suggestions?
The easiest solution to this is to hook your add calls on to the last action which gets fired before the rules are rebuilt during the flush process.
The first part of the flushing process is to delete the rewrite_rules option. When this happening the following actions will fire:
Note: If there is no rewrite_rules option in the db then these actions are not fired so you will also need to ensure to register your rules when someone calls get_option(‘rewrite_rules’) and it is going to return an empty string – there are similar filters in get_option you can use for this.