So I’m not sure if I’m not understanding how rewrite rules should work or not. I would like to a number of links such as example.com/clubA and example.com/clubB that redirect to example.com/venue-details/clubA where venue-details is a page.
The following code more or less does this:
add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter('init','flushRules');
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules(false);
}
function my_insert_rewrite_rules( $rules )
{
$newrules = array();
// NB plan is to eventually loop through a DB table to generate rules for lots of clubs / venues.
$newrules['clubA'] = 'index.php?pagename=venue-details';
return $newrules + $rules;
}
Now what I was expecting was that ones the rules had been generated they would be permanently saved/cached so that generating the rules wouldn’t be needed for every page load. for example, add the rules when your plugin is activated, set and forget. But whatever I do they never stick around?
Is my expectation wrong and if not, how would I accomplish the persistence of rules?
Thanks
Josh
Hooking the init action
add_filter('init','flushRules');
will lead to the rewrite rules being flushed with every page load.Instead you should call
$wp_rewrite->flush_rules
once, when your plugin is installed, by using the following:Remove the second filter hook and still keep the first filter hook, you already have:
That will lead to the custom rewrite rules being generated, when your activation function is called and also if some other plugin or an admin flushes the rewrite rules.