I see a lot of example showing to call add_rewrite_rule in your init hook, e.g.

function add_my_custom_rewrite()
{
   add_rewrite_rule(...
}

add_action('init', 'add_my_custom_rewrite');

and in your plugin activation hook,

register_activation_hook( __FILE__, 'my_plugin_activation');

function my_plugin_activation()
{
   add_my_custom_rewrite();
   flush_rewrite_rules(false);
}

So, when your plugin is activated, you rewrite will be flushed into db, seems working, but, there is a main problem

It still not solve the issue to remove the rewrite when people deactivate your plugin, you cannot simply place flush_rewrite_rules in your deactivation hook since init was already called before deactivate, and there is no way to remove existing rewrite rule., e.g.

register_deactivation_hook( __FILE__, 'my_plugin_deactivation');

function my_plugin_deactivation()
{
   flush_rewrite_rules(false); // will not work, since init (hence add_my_custom_rewrite) was already called at this point
}

Are there better way to solve the conflict between add_rewrite_rule, plugin activation and plugin deactivation?

1 Answer
1

The problem with calling flush_rewrite_rules() is that the rules instantly get regenerated, while your plugin’s hooks are still active.

What I usually do, because it’s the simplest route to success, is delete the rewrite_rules option on activation/deactivation. The rules will then get regenerated on the next pageload instead of the current one:

register_deactivation_hook( __FILE__, 'my_plugin_deactivation');
function my_plugin_deactivation() {
   delete_option( 'rewrite_rules' );
}

A more ideal solution is to remove your rules from the stack before flushing, but that’s kind of a pain to do (see https://core.trac.wordpress.org/ticket/29118).

Leave a Reply

Your email address will not be published. Required fields are marked *