Last active
August 29, 2015 14:01
-
-
Save michaellehmkuhl/2be48665bcb90fd09467 to your computer and use it in GitHub Desktop.
Root relative asset URLs for WP
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
function use_root_relative_url($input) { | |
$output = preg_replace_callback( | |
'!(https?://[^/|"]+)([^"]+)?!', | |
create_function( | |
'$matches', | |
// if full URL is site_url, return a slash for relative root | |
'if (isset($matches[0]) && $matches[0] === site_url()) { return "/";' . | |
// if domain is equal to site_url, then make URL relative | |
'} elseif (isset($matches[0]) && strpos($matches[0], site_url()) !== false) { return $matches[2];' . | |
// if domain is not equal to site_url, do not make external link relative | |
'} else { return $matches[0]; };' | |
), | |
$input | |
); | |
/** | |
* Fixes an issue when the following is the case: | |
* site_url() = http://yoursite.com/inc | |
* home_url() = http://yoursite.com | |
* WP_CONTENT_DIR = http://yoursite.com/content | |
* http://codex.wordpress.org/Editing_wp-config.php#Moving_wp-content | |
*/ | |
$str = "/" . end(explode("/", content_url())); | |
if (strpos($output, $str) !== false) { | |
$arrResults = explode( $str, $output ); | |
$output = $str . $arrResults[1]; | |
} | |
return $output; | |
} | |
if (!is_admin()) { | |
add_filter('script_loader_src', 'use_root_relative_url'); | |
add_filter('style_loader_src', 'use_root_relative_url'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment