digitalhydra
8/25/2016 - 11:04 PM

working multisite mapping

working multisite mapping

<?php

// Blog id to change
$id = 14;

// New URL to update blog 
$new_url = 'http://renoversity.com';

// Blog details
$details = get_blog_details( $id );
		
// Parse current blog URL
$parsed_scheme = parse_url( $details->siteurl, PHP_URL_SCHEME );

// Boolean to check if blog requested is main site	
$is_main_site = is_main_site( $id );

// Switch to requested blog
switch_to_blog( $id );

// Rewrite rules can't be flushed during switch to blog.
delete_option( 'rewrite_rules' );

// Change blog url
$blog_data = array( 'url' => $new_url ); //wp_unslash( $_POST['blog'] );

$blog_data['scheme'] = $parsed_scheme;

// Ensure requested blog is not main site
if ( $is_main_site ) {

	// On the network's main site, don't allow the domain or path to change.
	$blog_data['domain'] = $details->domain;
	$blog_data['path'] = $details->path;

} else {
	// For any other site, the scheme, domain, and path can all be changed. We first
	// need to ensure a scheme has been provided, otherwise fallback to the existing.
	$new_url_scheme = parse_url( $blog_data['url'], PHP_URL_SCHEME );

	if ( ! $new_url_scheme ) {
		$blog_data['url'] = esc_url( $parsed_scheme . '://' . $blog_data['url'] );
	}
	$update_parsed_url = parse_url( $blog_data['url'] );

	// If a path is not provided, use the default of `/`.
	if ( ! isset( $update_parsed_url['path'] ) ) {
		$update_parsed_url['path'] = '/';
	}

	$blog_data['scheme'] = $update_parsed_url['scheme'];
	$blog_data['domain'] = $update_parsed_url['host'];
	$blog_data['path'] = $update_parsed_url['path'];
}

$existing_details = get_blog_details( $id, false );

update_blog_details( $id, $blog_data );

// Maybe update home and siteurl options.
$new_details = get_blog_details( $id, false );

// Blog home url setting
$old_home_url = trailingslashit( esc_url( get_option( 'home' ) ) );
$old_home_parsed = parse_url( $old_home_url );

if ( $old_home_parsed['host'] === $existing_details->domain && $old_home_parsed['path'] === $existing_details->path ) {
	$new_home_url = untrailingslashit( esc_url_raw( $blog_data['scheme'] . '://' . $new_details->domain . $new_details->path ) );
	update_option( 'home', $new_home_url );
}

// Blog site url setting
$old_site_url = trailingslashit( esc_url( get_option( 'siteurl' ) ) );
$old_site_parsed = parse_url( $old_site_url );

if ( $old_site_parsed['host'] === $existing_details->domain && $old_site_parsed['path'] === $existing_details->path ) {
	$new_site_url = untrailingslashit( esc_url_raw( $blog_data['scheme'] . '://' . $new_details->domain . $new_details->path ) );
	update_option( 'siteurl', $new_site_url );
}

// Restore the current blog
restore_current_blog();
	
// for testing, remove later
echo 'site updated, new url is <a target="_blank" href="' . $new_site_url .'">' . $new_site_url . '</a>';