Skip to content

Instantly share code, notes, and snippets.

@blobaugh
Created October 16, 2018 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blobaugh/0c58c749732c0ba92daeeaed78b18cbf to your computer and use it in GitHub Desktop.
Save blobaugh/0c58c749732c0ba92daeeaed78b18cbf to your computer and use it in GitHub Desktop.
Fix the site urls on a WordPress Multisite
<?php
if( ! isset( $_GET['wds-replace-urls'] ) ) {
return;
}
add_action( 'init', function() {
global $wpdb;
$p = $wpdb->prefix;
/*
* The goal here is to replace all the site and home urls with their
* proper values. To get it to work is a little tricky. We need to do the
* following:
*
* - Get a list of all the sites from the blogs table with their domains and site id
* - Get a list of option tables with site ids and urls
* - Create the new urls
* - Update the option tables
*/
// Get a list of all the sites from the blogs table
$sql = "SELECT blog_id, CONCAT( domain, path ) AS url FROM `" . $p . "blogs`";
$sites = $wpdb->get_results( $sql );
// Create a list of good urls to check against later
$good_urls = [];
foreach( $sites as $s ) {
$good_urls[ $s->blog_id ] = untrailingslashit( set_url_scheme( "https://" . $s->url ) );
}
// Get a list options tables
$sql = "SELECT table_name FROM information_schema.tables where table_schema='" . DB_NAME . "' AND table_name LIKE '" . $p . "%options'";
$tables = $wpdb->get_results( $sql );
// Ok, now we get to loop thorugh the tables and verify the urls
$bad_url_count = 0;
foreach( $tables as $t ) {
$blog = explode( '_', $t->table_name );
if( ! is_numeric( $blog[1] ) ) {
continue; // Root site or no idea. Bail on this one
}
$blog_id = $blog[1];
unset( $blog ); // lil cleanup to make the server happy
// Get the siteurl for verification
$sql = "SELECT option_value AS url FROM " . $t->table_name . " WHERE option_name='siteurl'";
$siteurl = $wpdb->get_var( $sql );
// Now the fun part, we get to compare the site url with the good url
if( $siteurl === $good_urls[ $blog_id ] ) {
continue; // good! nothing to do here!
}
echo "<br/>Site " . $blog_id . " does not match urls (good) " . $good_urls[ $blog_id ] . " with " . $siteurl;
$bad_url_count++;
if( isset( $_GET['dryrun'] ) ) {
continue;
}
// Update siteurl with good url
$sql = "UPDATE " . $t->table_name . " SET option_value='" . $good_urls[ $blog_id ] . "' WHERE option_name='siteurl'";
$wpdb->query( $sql );
// Update home with good url
$sql = "UPDATE " . $t->table_name . " SET option_value='" . $good_urls[ $blog_id ] . "' WHERE option_name='home'";
$wpdb->query( $sql );
}
die( "<br/><br/>" . $bad_url_count . " urls replaced" );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment