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 ;)
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!
Doesn’t have to be in the loop, uses the permalinks settings to print out the full url to the page (http/https://website_url/permalinks_style_url). Check out the code or the function reference.
And yeah, ignores the querystring *Lol*
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 callingget_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 ofhome_url
which makes it work equally well in both ?p= and /whatever/post-name/ style permalinks too. Thanks again for your input!It’s a damn shame how complex it is though, I hope something as simple as that finds it way to core.
[…] https://konstantin.blog/2012/01/current-url-in-wordpress-3754/ ← Previous Post […]
[…] How to Get the Current URL in WordPress – 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, .. […]
[…] How to Get the Current URL in WordPress – via Konstantin Kovshenin […]