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));

4 thoughts on “How to Get the Current URL in WordPress

  1. If you’re using this in distributed code (i.e. plugin or theme), you also need to check whether permalinks are in use. If they’re not, you need to pass the query string to add_query_arg. Example:

    global $wp, $wp_rewrite;

    $query_args = $wp_rewrite->using_permalinks() ? array() : $wp->query_string;
    $current_url = esc_url_raw( home_url( add_query_arg( $query_args, $wp->request) ) );

    Seems like there should be a nicer way of doing this.

    Cheers,
    Eric

Leave a Reply

Your email address will not be published. Required fields are marked *