Default category link for a custom category is a broken link

I found that the reason flush_rewrite_rules(); wasn’t working was because switch_to_blog doesn’t re-initialize some of the properties of $wp_rewrite (not to mention other parts of WP), so flush_rewrite_rules was still generating some of the rules based on the permalink structure of the current blog (which is not the same), rather than the switched-to blog (84). Even calling $wp_rewrite->init(); doesn’t update the $extra_permastructs property of wp_rewrite – which is where all the default taxonomy paths are!

I had to trace back where $extra_permastructs is set up, and it turns out that’s setup by various calls to $wp_rewrite->add_permastruct – fortunately for me, since we don’t have many plugins installed, the only relevant calls to that function are from an init hook called create_initial_taxonomies. So this did the trick:

add_action('switch_blog', function() {
  global $wp_rewrite;
  $wp_rewrite->init();
  create_initial_taxonomies();
});

//[...]

switch_to_blog($new_blog_id);
flush_rewrite_rules();
restore_current_blog();

However… as I have just been informed by @skeltoac at WP, simply deleting the rewrite_rules option causes WordPress to automatically regenerate the rules the next time someone loads any page on that blog (and since it’s on the new blog, they are generated from the correct permalink structure). So a simpler solution is:

switch_to_blog($new_blog_id);
delete_option('rewrite_rules');
// This option is automatically regenerated the next time someone loads the new blog!
restore_current_blog();

In fact, I don’t even know why the flush_rewrite_rules method exists – it should just delete the rewrite_rules.

However – in case anybody ever needs to actually edit rewrite rules on another blog without flushing them for some reason, maybe the above will be helpful.

Perhaps, for instance, if you may have hundreds of rewrites, and you don’t want to make the next unlucky visitor wait for them all to be regenerated during the init phase of their request. However, if you have that many, there’s a good chance you have other $extra_permastructs that you will need to account for in the switch_blog action (unless you just have a lot of taxonomies) 🙂