Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active November 5, 2017 03:30
Show Gist options
  • Save CMCDragonkai/7578784 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/7578784 to your computer and use it in GitHub Desktop.
Wordpress: Automatic Url and Content Dir/Url Detection for Wordpress Composer Installs. Add to the top of the wp-config.php script.
<?php
/**
* Automatic Url + Content Dir/Url Detection for Wordpress
*/
$document_root = rtrim(str_replace(array('/', '\\'), '/', $_SERVER['DOCUMENT_ROOT']), '/');
$root_dir = str_replace(array('/', '\\'), '/', __DIR__);
$wp_dir = str_replace(array('/', '\\'), '/', __DIR__ . '/wp');
$wp_content_dir = str_replace(array('/', '\\'), '/', __DIR__ . '/wp-content');
$root_url = substr_replace($root_dir, '', stripos($root_dir, $document_root), strlen($document_root));
$wp_url = substr_replace($wp_dir, '', stripos($wp_dir, $document_root), strlen($document_root));
$wp_content_url = substr_replace($wp_content_dir, '', stripos($wp_content_dir, $document_root), strlen($document_root));
$scheme = (isset($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] != 'off' AND !$_SERVER['HTTPS']) ? 'https://' : 'http://';
$host = rtrim($_SERVER['SERVER_NAME'], '/');
$port = (isset($_SERVER['SERVER_PORT']) AND $_SERVER['SERVER_PORT'] != '80' AND $_SERVER['SERVER_PORT'] != '443') ? ':' . $_SERVER['SERVER_PORT'] : '';
$root_url = $scheme . $host . $port . $root_url;
$wp_url = $scheme . $host . $port . $wp_url;
$wp_content_url = $scheme . $host . $port . $wp_content_url;
define('WP_HOME', $root_url); //url to index.php
define('WP_SITEURL', $wp_url); //url to wordpress installation
define('WP_CONTENT_DIR', $wp_content_dir); //wp-content dir
define('WP_CONTENT_URL', $wp_content_url); //wp-content url
@mems
Copy link

mems commented May 29, 2014

Be aware that $_SERVER['DOCUMENT_ROOT'] could be different to __DIR__:

echo $_SERVER['DOCUMENT_ROOT'];
→ /homez.xxx/some/path
echo __DIR__;
→ /home/some/path

especially on shared web hosting service (like OVH).
To fix that, use realpath() to resolve symlink:

echo realpath($_SERVER['DOCUMENT_ROOT']);
→ /home/some/path

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment