Wordpress - How to use relative links on my pages?

WordPress has a built-in function for removing protocol and domain from absolute URLs, wp_make_link_relative, located in /wp-includes/formatting.php:

function wp_make_link_relative( $link ) {
    return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
}

To apply this function to (e.g.) permalinks, simply add a filter, as such:

add_filter( 'the_permalink', 'wp_make_link_relative' );

Deluxe Blog Tips shows how to apply this to various types of links, while making sure feed and sitemap links aren't affected:

add_action( 'template_redirect', 'rw_relative_urls' );
function rw_relative_urls() {
    // Don't do anything if:
    // - In feed
    // - In sitemap by WordPress SEO plugin
    if ( is_feed() || get_query_var( 'sitemap' ) )
        return;
    $filters = array(
        'post_link',
        'post_type_link',
        'page_link',
        'attachment_link',
        'get_shortlink',
        'post_type_archive_link',
        'get_pagenum_link',
        'get_comments_pagenum_link',
        'term_link',
        'search_link',
        'day_link',
        'month_link',
        'year_link',
    );
    foreach ( $filters as $filter )
    {
        add_filter( $filter, 'wp_make_link_relative' );
    }
}

$my_url = 'my/relative/url.php';
echo site_url($my_url);

site_url() when used by itself will return the absolute path to your blog. But, if you add an argument to it, as per my example above, it will prepend the absolute path to your path. Just make sure your URL doesn't contain a leading slash (eg: /this/may/not/work).

Finally, if you happen to have your wordpress installed in your server's root, you can use a server-relative path (this uses the leading slash to indicate starting at the server root). So if your blog is installed at http://www.me.com/blog then you can access your relative links safely with /blog/my_link.php.


two ways to do that:

  • Linking Without Using Permalinks

  • Linking Using Permalinks