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

Why Files with Identical Content (*.js, *.php, *.css) Can Have Different Sizes?

When developers compare files with identical content but notice that their sizes differ, it can be perplexing. Let’s explore why this happens and what factors influence the size of files with extensions like *.js, *.php, and *.css. 1. File Encoding One of the key factors affecting file size is text encoding. The most common encodings…
Read more

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more