How to Get the Current URL in WordPress

Here’s a quick tip! I was wandering around the web for the perfect solution to retrieve the current URL in a WordPress theme or plugin. I found a bunch of solutions for PHP, but not directly related to WordPress so I thought there has to be an easier way, and after a few hours of examining with global variables seems like I found it.

global $wp;
$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );

Beats all the $_SERVER approaches and no need to identify whether the host is using SSL, etc. You can add a trailing slash to that with trailingslashit if you need to, and it looks much cleaner too. Hope you enjoy that, and thanks for tweeting ;)

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

  1. I assume this doesn’t need to be in the loop. Does it return the current URL in the default (numeric) permalink or the style set in settings > permalinks?

    • Brent, yieks good catch. I edited the code so that the query string is appended to the URL unless it’s empty, this makes it work for when default permalinks structure is used. Thanks for the tip!

    • It doesn’t use the permalinks settings per se but I’m sure the WP class does at some point. Query string yeah, totally forgot about that. Thanks for the heads up!

    • You’re right on that, all it does is take the wp->request parameter, filter it, prepend the correct scheme and site url. Does the dirty work for you.

      The permalink setting on the other hand is going to affect how the URL is rewritten. You’ll find that ?p= is rewritten according to your current permalink settings.

      Calling home_url() is similar to calling get_home_url(null, $wp->request, null) (home_url calls get_home_url, the parameters differ).

    • Correct Egill, hopefully the add_query_arg will append the query string to the result of home_url which makes it work equally well in both ?p= and /whatever/post-name/ style permalinks too. Thanks again for your input!

  2. How to Get the Current URL in WordPress |

  3. Tweet-Parade (no.2 Jan 2012) |

  4. Seven Links for Sunday #6

Comments are closed.