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 Settings → Permalinks, 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();
}