Last active
January 19, 2025 17:52
-
-
Save gsarig/8f6d4dff0b8a9e70a6704e755c38fd30 to your computer and use it in GitHub Desktop.
Auto-detect MySQL Port for LocalWP Projects in WSL and Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$user = <YOUR_WINDOWS_USERNAME>; | |
$sites_dir = '/local-sites/'; // The LocalWP sites directory | |
// Detect environment (Windows vs WSL) and set appropriate path | |
$is_windows = stripos(PHP_OS, 'WIN') === 0; | |
$sites_json_path = $is_windows | |
? "C:/Users/$user/AppData/Roaming/Local/sites.json" | |
: "/mnt/c/Users/$user/AppData/Roaming/Local/sites.json"; | |
// Parse the JSON file | |
$sites = json_decode(file_get_contents($sites_json_path), true); | |
if ($sites === null) { | |
error_log("Failed to parse sites.json from path: $sites_json_path", 0); | |
exit; | |
} | |
// Get the working directory relative to the Local sites folder | |
$current_directory = getcwd(); | |
if ($is_windows) { | |
$current_directory = str_replace('\\', '/', $current_directory); // Normalize Windows paths | |
} | |
// Locate the Local sites directory in the current path | |
$local_sites_position = strpos($current_directory, $sites_dir); | |
if ($local_sites_position === false) { | |
error_log("Error: Could not find the Local sites directory in the path: $current_directory", 0); | |
exit; | |
} | |
// Extract the site name from the path | |
$site_name = explode('/', substr($current_directory, $local_sites_position + strlen($sites_dir)))[0]; | |
// Find the MySQL port for the site | |
$db_port = null; | |
foreach ($sites as $site) { | |
if ($site['name'] === $site_name) { | |
$db_port = $site['services']['mysql']['ports']['MYSQL'][0]; | |
break; | |
} | |
} | |
if ($db_port) { | |
define('DB_HOST', '127.0.0.1:' . $db_port); | |
} else { | |
error_log("Error: Could not find MySQL port for site '$site_name'. Falling back to localhost.", 0); | |
define('DB_HOST', 'localhost'); | |
} | |
/* | |
How to use: | |
On the `wp-config.php` of your site, comment out or remove the line: | |
define( 'DB_HOST', 'localhost' ); | |
and add the following in its place: | |
$is_windows = stripos(PHP_OS, 'WIN') === 0; | |
$config_script_path = $is_windows | |
? '<WINDOWS_PATH_TO_YOUR_SCRIPT>/localwp-dynamic-db-config.php' | |
: '/mnt/<LINUX_PATH_TO_YOUR_SCRIPT>/localwp-dynamic-db-config.php'; | |
require $config_script_path; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment