0

I created a function in functions.php that adds some rewrite rules:

function add_rewrite_rules() { 
    add_rewrite_rule('events/page/([0-9])*/?', 'index.php?pagename=events&paged=$matches[1]', 'top');
    [...]   
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

I would like to execute it every time any plugin is activated, so if the new rules get overwritten I can restore them automatically. Is it possible?

Thank you.

2
  • what happens if someone visits the permalinks settings page (which triggers a flush)? it's not just plugin activation you need to worry about.
    – Milo
    Commented May 8, 2014 at 17:13
  • So what should I do? Commented May 8, 2014 at 17:47

3 Answers 3

2
  1. Add your rewrite rules on the init action hook.

  2. In your personal activation function, both a) add the rewrite rules and b) flush the rewrite rules. One time. This is the only time you need to flush the rules.

Alternatively, if your rewrite rules can change through user input, then you need to flush them when the rules change, not at any other time. You still need to add them on init though.

3
  • I added the rules on the init hook. They don't change through user input, but I think they can change if WP core is updated or on the update of some plugins. Should I flush them using the generate_rewrite_rules hook or is it unecessary? Commented May 9, 2014 at 8:53
  • You only need to flush them when they change, period. Adding them on init is fine the rest of the time.
    – Otto
    Commented May 10, 2014 at 3:48
  • Clear. How do I automatically flush them when they change? Commented May 12, 2014 at 15:41
1

Hook your function on the init hook so it is always present-

function wpd_add_rewrite_rules() { 
    add_rewrite_rule('events/page/([0-9])*/?', 'index.php?pagename=events&paged=$matches[1]', 'top');
}
add_action( 'init', 'wpd_add_rewrite_rules' );

See the examples in Codex for flush_rewrite_rules for where to flush rules when you've added them, either in plugin activation or theme switch. Do not flush rewrite rules on init.

0

I wonder if this will work:

add_action( 'activated_plugin', function(){

    // your stuff here

}, PHP_INT_MAX );

where the hook activated_plugin is fired after a plugin is activated.

2
  • Thanks: it works. I'm wondering how I could get that rule work with generate_rewrite_rules hook, so that I'm sure the rule is added after all rewrite rules have been created. Commented May 8, 2014 at 17:15
  • Did you check out the rewrite_rules_array filter that's fired just after the generate_rewrite_rules filter? It filters all the rewrite rules array and "fires after the rewrite rules are generated".
    – birgire
    Commented May 8, 2014 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.