public static function get_by_domain($domains)
{
global $wpdb;
$domains = (array) $domains;
// Check cache first
$not_exists = 0;
foreach ($domains as $domain) {
$data = wp_cache_get('domain:' . $domain, 'domain_mapping');
if (!empty($data) && $data !== 'notexists') {
return new static($data);
} elseif ($data === 'notexists') {
$not_exists++;
}
}
if ($not_exists === count($domains)) {
// Every domain we checked was found in the cache, but doesn't exist
// so skip the query
return null;
}
$placeholders = array_fill(0, count($domains), '%s');
$placeholders_in = implode(',', $placeholders);
// Prepare the query
$query = "SELECT * FROM {$wpdb->dmtable} WHERE domain IN ({$placeholders_in}) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1";
$query = $wpdb->prepare($query, $domains);
// Suppress errors in case the table doesn't exist
$suppress = $wpdb->suppress_errors();
$mapping = $wpdb->get_row($query);
$wpdb->suppress_errors($suppress);
if (empty($mapping)) {
// Cache that it doesn't exist
foreach ($domains as $domain) {
wp_cache_set('domain:' . $domain, 'notexists', 'domain_mapping');
}
return null;
}
wp_cache_set('domain:' . $mapping->domain, $mapping, 'domain_mapping');
return new static($mapping);
}
/** * Register filters for URLs, if we've mapped */ function register_mapped_filters() { $current_site = $GLOBALS['current_blog']; $real_domain = $current_site->domain; $domain = $_SERVER['HTTP_HOST']; if ($domain === $real_domain) { // Domain hasn't been mapped return; } // Grab both WWW and no-WWW if (strpos($domain, 'www.') === 0) { $www = $domain; $nowww = substr($domain, 4); } else { $nowww = $domain; $www = 'www.' . $domain; } $mapping = Mapping::get_by_domain(array($www, $nowww)); if (empty($mapping) || is_wp_error($mapping)) { return; } $GLOBALS['mercator_current_mapping'] = $mapping; add_filter('site_url', __NAMESPACE__ . '\\mangle_url', -10, 4); add_filter('home_url', __NAMESPACE__ . '\\mangle_url', -10, 4); // If on network site, also filter network urls if (is_main_site()) { add_filter('network_site_url', __NAMESPACE__ . '\\mangle_url', -10, 3); add_filter('network_home_url', __NAMESPACE__ . '\\mangle_url', -10, 3); } }