How to reset permanent links on all sites in the WordPress network (Multisite)

Quite often we encounter a situation when something breaks the structure of permanent links on all sites in the WordPress network (Multisite installation), for example, when a plugin activation error occurs throughout the network.

On one site from the network, this is easy enough to fix by manually going into SettingsPermalinks, which will reset and restore the rewrite rules, but if there are dozens of sites on the network, this is no longer practical and you need a way to do this automatically for all sites.

Typical approach

Most of the attempts we have seen have worked something like this:

/*
 * This is an example of the WRONG way to reset permanent links, don't use it!
 * Use the best way described below.
 */

function wpz_wrong_flush_rewrite_rules_on_multisite() {

	global $wp_rewrite;
	$sites = wp_get_sites( array( 'limit' => false ) );

	foreach ( $sites as $site_id ) {
		switch_to_blog( $site_id );
		$wp_rewrite->init();
		flush_rewrite_rules(); // You can't do that after calling switch_to_blog().
		restore_current_blog();
	}
	$wp_rewrite->init();

}

The function will work for the basic POST and PAGE record types, but it won’t have any effect on custom CPT record types, because switch_to_blog() has some limitations, and plugins are one of those things.

If you’re using a multisite and you have custom record types (CPTs) that are registered with third-party plugins, then using flush_rewrite_rules() makes no sense!

Best way

Simply delete the rewrite_rules option, because it will be automatically re-generated the next time your site is loaded.

$sites = get_sites( array(
    'number'  => 10000,
    'public'  => 1,
    'deleted' => 0,
) );

foreach ( $sites as $site ) {
    switch_to_blog( $site->blog_id );
    delete_option( 'rewrite_rules' );
    restore_current_blog();
}

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more