Hooking “delete_option_rewrite_rules” for rewrite rule addition

See 2015.07.24 and 2017.01.25 Updates Bellow…


I’m trying to find the most efficient way to ensure my word press “rewrite rules” are set correctly in the event that another plugin calls the flush_rules() function.

Read More

Traditionally I’ve seen instructions on adding the rules on every page load of your plugin (eg here)

add_action('wp_loaded','define_rules_here');
function define_rules_here()
{
  add_rewrite_rule($foo,$bar,$yams);
}

My concern is the way I’ve written my plugin is the rewrite rules are configurable by the user, and that having to load the options from the database for every page load seems inefficient.

I’ve found little information on the following, but it seems just as valid…

add_action('delete_option_rewrite_rules','define_rules_here');
function define_rules_here()
{
  add_rewrite_rule($foo,$bar,$yams);
}

What I’ve found is that the first thing flush_rules() calls is delete_option('rewrite_rules'); which seems to trigger my hook quite nicely as the delete_option function ends with a do_action( "delete_option_$option", $option ); call.

My question is: Is there anything fundamentally wrong with this approach of hooking into the “delete_option_rewrite_rules” action?


Update 2015.07.24:

Using delete_option_rewrite_rules is bad because it’s not fired off if the option has been deleted via some other means, instead I have hooked delete_option with the $option parameter because its ALWAYS fired off prior to option delete unlike delete_option_* which is conditional based on the database result.

add_action('delete_option','handle_deleted_option');
function handle_deleted_option($option)
{
  if($option === 'rewrite_rules')
  {
    define_rules_here();
  }
}
function define_rules_here()
{
  add_rewrite_rule($foo,$bar,$yams);
}

Update 2017.01.25:

You should also add support for add_action('update_option','handle_deleted_option'); as wordpress changed re-write rules into updating instead of deleting then inserting.

Related posts

Leave a Reply

1 comment

  1. Set the option that stores the rewrite configuration to autoload via the 4th argument of add_option:

    add_option( 'my_plugin_option', $my_plugin_options, '', 'yes' );
    

    It’ll get loaded and cached with the query that already runs on every page load, so it’s a non-issue.

    Then you can add your rewrite rules on the correct hook, which is init, and you won’t have to worry about it.