Changing the visible url path to css & js files

Does anyone happen to know how I can automatically turn:

http://www.example.com/wp-content/themes/theme-name/css/stylesheeet.css

into

http://www.example.com/css/stylesheet.css

Naturally I could just create the applicable folder within the root of the website, place the files there and just reference them but that is now what I am after.

I am looking for a way to keep all CSS & JavaScript files within the theme folder but I would like for wordpress to show the above outlined url path if you view the source of the page.

In an ideal situation I am looking for a piece of code which can be added that automatically does this for all files referenced within my theme folder including any images.

2 Answers
2

Offhand I think you’d need two things:

First, a rewrite rule in your .htaccess file like so:

RewriteEngine On
RewriteBase /
RewriteRule ^css/(.*) /wp-content/themes/theme-name/css/$1 [L]
RewriteRule ^js/(.*) /wp-content/themes/theme-name/js/$1 [L]

Second, add a filter to your theme’s functions.php like so:

function change_css_js_url($content) {
    $current_path="/wp-content/themes/theme-name/";
    $new_path="https://wordpress.stackexchange.com/"; // No need to add /css or /js here since you're mapping the subdirectories 1-to-1
    $content = str_replace($current_path, $new_path, $content);
    return $content;
}
add_filter('bloginfo_url', 'change_css_js_url');
add_filter('bloginfo', 'change_css_js_url');

A couple caveats:
– if a plugin or something doesn’t use bloginfo() or get_bloginfo() it will not trigger the filter. You can get around this by hooking your function into other filters as needed.
– some plugins/themes/etc use a hard-coded paths. There’s not much you can do about this except modify the code to use one of WP’s functions to get the path.

Here’s the same example using the twentyten theme (no css/js subdirectories, but the idea is the same.)

.htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^twentyten/(.*) /wp-content/themes/twentyten/$1 [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

functions.php

function change_css_js_url($content) {
    $current_path="/wp-content/themes/";
    $new_path="https://wordpress.stackexchange.com/"; // No need to add /css or /js here since you're mapping the subdirectories 1-to-1
    $content = str_replace($current_path, $new_path, $content);
    return $content;
}
add_filter('bloginfo_url', 'change_css_js_url');
add_filter('bloginfo', 'change_css_js_url');

Leave a Comment