flush_rewrite_rules()WP 3.0.0

Remove rewrite rules and then recreate rewrite rules.

1 time — 0.010174 sec (extremely slow) | 50000 times — 196.39 sec (extremely slow) | PHP 7.1.11, WP 4.9.8

No Hooks.

Return

null. Nothing (null).

Usage

flush_rewrite_rules( $hard );
$hard(true|false)
Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush).
Default: true (hard)

Examples

0

#1 Refresh Friendly URL rules on plugin activation/deactivation

Example, shows how to reset rewrite rules Friendly URL at the moment of plugin activation/deactivation:

register_activation_hook( __FILE__, 'myplugin_activate' );
register_deactivation_hook( __FILE__, 'myplugin_deactivate' );

function myplugin_activate() {

	// Here, we do what we need to do when activating the plugin

	flush_rewrite_rules();
}

function myplugin_deactivate() {
	flush_rewrite_rules();
}
0

#2 Flush Rules on theme activation/deactivation

This example shows how to reset the Friendly URL rewrite rules when the theme is activated:

/* Reset rewrite rules. */
add_action( 'after_switch_theme', 'bt_flush_rewrite_rules' );

function bt_flush_rewrite_rules() {
	 flush_rewrite_rules();
}
0

#3 Reset Friendly URL if file has been changed or every 48 hours

If you're developing a theme, a code that will reset the Friendly URL rewrite rules if the file has been changed or every 48 hours might be useful while you're developing it.

// do not use on live/production servers
add_action( 'init','maybe_rewrite_rules' );

function maybe_rewrite_rules() {

	// do it in admin only
	if( ! is_admin() ){
		return;
	}

	// Get the file time as the version number
	$ver = filemtime( __FILE__ );
	$defaults = [ 'version' => 0, 'time' => time() ];
	$r = wp_parse_args( get_option( __CLASS__ . '_flush', [] ), $defaults );

	// reset if the version has changed if 48 hours have passed.
	if ( $r['version'] != $ver || $r['time'] + 172800 < time() ) {
		flush_rewrite_rules();

		$args = array( 'version' => $ver, 'time' => time() );
		if ( ! update_option( __CLASS__ . '_flush', $args ) )
			add_option( __CLASS__ . '_flush', $args );
	}

}

“Flushing” the rewrite rules should only happen in wp-admin, see https://core.trac.wordpress.org/ticket/44142. It is possible to do from the front-end while developing a theme or a plugin, but is a pretty bad idea if ever done in production.

Notes

  • Global. WP_Rewrite. $wp_rewrite WordPress rewrite component.

Changelog

Since 3.0.0 Introduced.

flush_rewrite_rules() code WP 6.5.3

function flush_rewrite_rules( $hard = true ) {
	global $wp_rewrite;

	if ( is_callable( array( $wp_rewrite, 'flush_rules' ) ) ) {
		$wp_rewrite->flush_rules( $hard );
	}
}