Removes rewrite rules and then recreate rewrite rules.
Parameters
$hard
booloptional- Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard).
Default:
true
Source
function flush_rewrite_rules( $hard = true ) {
global $wp_rewrite;
if ( is_callable( array( $wp_rewrite, 'flush_rules' ) ) ) {
$wp_rewrite->flush_rules( $hard );
}
}
Changelog
Version | Description |
---|---|
3.0.0 | Introduced. |
wc_get_page_id( '' )
, and then run a flush_rewrite_rules, but at the point register_activation_hook() is called, WC isn’t even initialized, so I used your code to run the flush_rewrite_rules delayed enough and still only call it once after my plugin’s installation! Thank you very much for the idea!If you want to flush rules while updating posts based on post type:
A relatively simple way to flush rewrite rules on activation and deactivation hooks is not using flush_rewrite_rules() at all. Instead just clear the rewrite_rules option to force WordPress to recreate them at the right time.
Example:
This avoids having to do complicated stuff like registering your custom post types in the activation hook or throwing and catching dedicated db option or transients as suggested in other notes…
flush_rewrite_rules()
when not called at the right time: it not only removes the old rewrite rules but also creates new ones, based on the (custom) post types and rewrite rules filters registered registered at that point in time. So if your plugin or theme callsflush_rewrite_rules()
on an awkward moment where not everything is in place, wrong or incomplete rewrite rules will be generated. For example: when updating a plugin setting that warrants new rewrite rules, callingflush_rewrite_rules()
from withing the option sanitization hook will likely cause problems. Or when calling it on a deactivation hook, without first removing your custom post type,flush_rewrite_rules()
will likely not have the desired effect. Others like @nsrw0rk (up voted for good reason) have suggested an elegant solution: save an option to the database that will triggerflush_rewrite_rules()
on the next init. But this will not always work, like in case of the deactivation hook (where the next init will be without your plugin) or in Multisite mode where rewrite rules can’t be flushed during switch to blog. So that is why I suggested the less elegant, but effective work-around:delete_option( 'rewrite_rules' )
:)This is how you would flush rules on theme activation:
This is how you would flush rewrite rules when a plugin is activated or deactivated:
If you’re developing a theme, while building it you can use this snippet of code that will flush rewrite rules when the file containing it is changed, or every 48 hours:
if ( ! is_admin() ) { return; }
at the top of the above function.