How to Get the Current URL in WordPress

Note: The original post wouldn’t work for WordPress on sub-domains, so I’ve updated it to include a solution that will

The other day I needed to get the current url the user was on – and I was convinced that there would be a better way than handling $_SERVER directly.

I found this solution by Konstantin Kovshenin, but which unfortunately gave me

http://example.com/blog/category/cata1?category_name=cata1 

when on

http://example.com/blog/category/cata1

Now add_query_arg, when passed no url uses the current url but, unfortunately, when on www.example.com/page/subpage/ it gives you: /page/subpage/. To get around that, you can use home_url.

To get the ‘current url’ in WordPress:

 $current_url = home_url(add_query_arg(array()));

Unfortunately if you WordPress install lives on a subdomain this won’t work, since:

  • home_url() gives you something like www.example.com/blog
  • add_query_arg(array()) gives you something like blog/page/subpage

So you get a repeat of blog. A more general solution would be

 $current_url = home_url(add_query_arg(array(),$wp->request));