Support » Plugins » Hacks » Force rewrite rules when updating in Multisite

  • In many of my WP sites, custom post type and taxonomy URLs return 404 errors right after certain updates. Fixing this is as easy as flushing rewrite rules visiting the Permalinks page, but when you’re updating multiple sites at once this can be very annoying.

    So I thought a possible solution could be to force a flush right after any plugin, theme or core update. And I came pretty close:

    function flush_after_update() {
    	global $wp_rewrite;
    	//If multisite, we loop through all sites
    	if (is_multisite()) {
    		global $wpdb;
    		//Pick up all active sites
    		$sites = $wpdb->get_results( $wpdb->prepare( "SELECT blog_id, domain FROM wp_blogs WHERE archived = '0' AND spam = '0' AND deleted = '0' ORDER BY blog_id", '' ) );
    		//Loop through them
    		foreach ($sites as $site) {
    			//Switch to current site
    			//Rebuild rewrite rules for this site
    			//Flush them
    			echo 'Rewrite rules flushed for site ' . $site->blog_id . ' (' . $site->domain . ').<br />';
    		//Back to normal
    	} else {
    		//Flush rewrite rules
    		echo 'Rewrite rules flushed.';
    //Hook it up
    add_filter('upgrader_post_install', 'flush_after_update', 10, 2);

    The single-site part works just fine. The problem is in Multisite, and I think it is because $wp_rewrite->init() doesn’t bring the rules for custom post types and taxonomies.

    What do you think? Can this code be fixed? Does anyone have a better approach?

    Thanks in advance,


Viewing 3 replies - 1 through 3 (of 3 total)
  • I’ve been looking for this also. I haven’t been able to get anything to work yet, but I found this article, which I thought might be useful.

    Specifically, it says:

    However, there is a fly in the ointment. When we change blogs using set_blog_id, we are only changing the database context. The global $wp_rewrite object remains the same, i.e., it is the $wp_rewrite object of the original blog from where we executed the network activate or deactivate.

    Seems like that’s the key, but I can’t figure out the code.

    Food for thought.

    Wait a minute. I just tried again and your original code seems to have worked this time.

    I added it to a functions file on a parent theme that all of my blogs are children of, then I went to the Network Admin page and updated one of the plugins via the WordPress Updates page and it worked!

    Not sure why it didn’t work the first time, but perhaps it has something to do with the Proper Network Activation plugin?

    I’ll test a little more…

    alturnwall: I believe this part

    //Rebuild rewrite rules for this site

    is what allows you to use the same object to flush the rules for all sites in the network

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Force rewrite rules when updating in Multisite’ is closed to new replies.