The flush_rewrite_rules()
WordPress PHP function removes current rewrite rules and recreates them. It can either update the .htaccess
file (hard flush) or just update the rewrite_rules
option (soft flush). The default mode is hard flush.
Usage
Here’s a basic example of how to use the function:
flush_rewrite_rules();
This will perform a hard flush of the rewrite rules. If you want a soft flush, you just need to pass false
to the function:
flush_rewrite_rules(false);
Parameters
$hard
(bool) (optional): Whether to perform a hard or soft flush. Default istrue
(hard flush).
More information
See WordPress Developer Resources: flush_rewrite_rules()
Please be cautious when using this function, as it can be resource-intensive. It’s best to use it sparingly and only when necessary, like on plugin activation or deactivation.
Examples
Activation Hook Example
When a plugin is activated, you can use this function to ensure the rewrite rules are flushed:
register_activation_hook( __FILE__, 'plugin_activation' ); function plugin_activation() { flush_rewrite_rules(); }
Deactivation Hook Example
Similarly, you can flush rewrite rules when a plugin is deactivated:
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
Custom Query Variable Example
You can add a custom query variable and then flush the rewrite rules:
add_action( 'init', 'custom_query_vars' ); function custom_query_vars() { global $wp; $wp->add_query_var( 'newfeed' ); flush_rewrite_rules(); }
Theme Activation Example
If you want to flush rewrite rules when a theme is activated, you can do so with this function:
add_action( 'after_switch_theme', 'flush_rewrite_rules' );
Post Saving Example
You can also flush rewrite rules when a specific post type is updated:
add_action( 'save_post', 'wpdoc_flush_rules_on_save_posts', 20, 2); function wpdoc_flush_rules_on_save_posts( $post_id, $post ) { if ( $post->post_type != 'post' ) { return; } flush_rewrite_rules(); }