How to get URL of current page displayed?

I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use echo get_permalink(), but that does not work on all pages. Some pages (e.g. my homepage) display several posts, and if I use get_permalink() on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL?

Can I attach get_permalink() to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete?


get_permalink() is only really useful for single pages and posts, and only works inside the loop.

The simplest way I’ve seen is this:

global $wp;
echo home_url( $wp->request )

$wp->request includes the path part of the URL, eg. /path/to/page and home_url() outputs the URL in Settings > General, but you can append a path to it, so we’re appending the request path to the home URL in this code.

Note that this probably won’t work with Permalinks set to Plain, and will leave off query strings (the ?foo=bar part of the URL).

To get the URL when permalinks are set to plain you can use $wp->query_vars instead, by passing it to add_query_arg():

global $wp;
echo add_query_arg( $wp->query_vars, home_url() );

And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings:

global $wp;
echo add_query_arg( $wp->query_vars, home_url( $wp->request ) );

Leave a Comment