Skip to content

Instantly share code, notes, and snippets.

@donut
Last active September 28, 2015 03:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donut/1381015 to your computer and use it in GitHub Desktop.
Save donut/1381015 to your computer and use it in GitHub Desktop.
Fix WordPress asset URLs when a non-absolute base URL is given
<?php
/**
* Fixes URLs to asset files.
*
* If SITE_URL is left blank then WordPress will assume that the SITE_URL is
* the current URL which causes problems when the current URL is not the root
* page. So, instead of linking to
* /wp-content/themes/themename/js/main.js it would link to
* /some-page-name/a-child-page/wp-content/themes/themename/js/main.js which
* breaks things. This attemps to fix this.
*
* This fix assumes that WordPress is installed in the root web directory for
* this domain.
*
* From: https://gist.github.com/1381015
*
* @author Donovan Mueller
* @param string $src
* @return string
*/
function themename_make_script_src_absolute($src)
{
// Remove the base_url if present
$base_url = wp_guess_url();
$pos = strpos($src, $base_url);
if ($pos === 0) {
$src = substr($src, strlen($base_url));
// If the base URL ended in a GET query string the desired asset SRC will
// be URL encoded. It must be decoded.
if (strpos($base_url, '?') !== false) {
$src = rawurldecode($src);
// Because this URL was appended to a GET query string if there was a
// GET query string attached to the asset URL it will start with &
// instead of ? which causes problems.
$src = preg_replace('`&`', '?', $src, 1);
}
}
// Add a leading slash if not present but should be.
if (preg_match('~^(?:/|https?://)~i', $src) === 0) {
$src = "/$src";
}
return $src;
} // themename_make_script_src_absolute()
add_filter('script_loader_src', 'themename_make_script_src_absolute');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment