How to make WordPress URLs root relative

For several reasons, including portability, reducing download size, and general code neatness, I like to make all links within a website root relative.

WordPress, on the other hand, seems to like absolute URLs for some reason. To clean this up a bit I have the following simple function in my functions.php file to strip the protocol and domain name from URL strings:

function make_href_root_relative($input) {
	return preg_replace('!http(s)?://' . $_SERVER['SERVER_NAME'] . '/!', '/', $input);

You can use this function by feeding it any URL string you want to make root relative. You can do this either in template files or in your functions.php file. Here’s an example of adding this function as a filter to the the_permalink() function:

function root_relative_permalinks($input) {
	return make_href_root_relative($input);
add_filter( 'the_permalink', 'root_relative_permalinks' );

After doing that, each time you use <?php the_permalink(); ?> in your templates, the resulting URL will be root relative, i.e. instead of you will get /page-or-post-url/. Much better.

Posted on October 25, 2010 in WordPress, Coding