Wordpress - Get Permalink without domain (i.e. get relative permalink)
I use
str_replace(home_url(), '', get_permalink());
If site root is not /
Use $_SERVER['REQUEST_URI']
instead of get_permalink()
to grab the current URL. get_permalink
will give you the full address of the current post, not the address of the URL visited.
e.g. for example.com/test/page echo $_SERVER['REQUEST_URI'];
prints /test/page
Note that this doesn't include the hashtag, as that part never gets sent to the server, and it also doesn't include ?foo=bar
type parameters, those are in the $_GET
array.
This works for me:
function force_relative_url ($url)
{
return preg_replace ('/^(http)?s?:?\/\/[^\/]*(\/?.*)$/i', '$2', '' . $url);
}
To use it on a permalink:
$relative_permalink = force_relative_url (get_permalink ($post->ID));