Search code examples
wordpressflushrules

Wordpress and flush_rules


I have a site with several custom rewrite rules like this:

add_action('init', array($this, 'add_my_rewrite') );

public function add_my_rewrite() {

    add_rewrite_tag('%get-continent%','([^&]+)');

    global $wp_rewrite;
    $wp_rewrite->add_rule('something/([^/]*)/?','index.php?page_id=12345&get-continent=$matches[1]','top');         
    $wp_rewrite->flush_rules(false);
}

I copied it from old codex example and searching here. They all work fine but they do lots and lots of update on the DB.

After doing a little research I found out that codex also discourage firing it on init (unlike in the example that was provided). It's a little broad on which hook should I fire it. After a little research appears that the best time is on plugin activation.

Question: I can't deactivate those plugins in the prod site, I can replace "init" with something else es. plugin activation (not sure yet what is the hook) but will the roules work if I comment it out? Do I have to fire it some other time other than on plugin activation? Isn't it going to be accidentally overwritten? Can I simpli comment out the add_action since I won't be activating or deactivating the plugin?

As always, thank you guys.


Solution

  • I commented out the $wp_rewrite->flush_rules(false); part, I had to leave this:

    add_action('init', array($this, 'add_my_rewrite'), 10, 0);
    

    and the function became:

    public function add_my_rewrite() {
    
        add_rewrite_tag('%get-continent%','([^&]+)');
    
        global $wp_rewrite;
        $wp_rewrite->add_rule('something/([^/]*)/?','index.php?page_id=12345&get-continent=$matches[1]','top');         
    }
    

    It works just fine, ideally I'll have to fire the flush on activation or eventually just go into Settings / Permalinks and hit Save.