I typically call the rewrite rules with this action
add_action('init', 'add_my_rewrite_rules')
But what I do not like about it is that the rewrite rules are written every time an init action is triggered, which means pretty much every time a page is refreshed.
Is this the correct action to call the rewrite rules? Is there a better way of handling that? (i.e, no need to add the rules every time we trigger init)
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
init is the recommended hook and no, the rewrite rules will not be overwritten each time the hook fires or that the page is loaded, unless if you call flush_rewrite_rules() or WP_Rewrite::flush_rules() in your callback.
add_action( 'init', 'add_my_rewrite_rules' );
function add_my_rewrite_rules() {
add_rewrite_rule( ... );
flush_rewrite_rules(); // don't do this
}
So please don’t do that, or do it only upon plugin/theme activation and deactivation — and if you don’t already know, you can easily flush the rules by simply going to the Permalink settings admin page, without having to hit the Save Changes button.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0