Get current page url in WordPress


Getting current page URL in WordPress isn’t that easy for starters. Most of the people use $_SERVER variable to get URL. I tried following one to get current URL to redirect it after login or logout.

$current_page_url = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

The problem with this code was that it wasn’t giving me queried object information on author.php template, so I was not able to get page title on required spot. It was happening on all archive templates.

Then I found a post from Konstantin Kovshenin about current page URL, and he gave a solution in a very good way.

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

It solved my problem and it is a way looks more like related to WordPress, and as Konstantin said on his site too, It beats all the approaches $_SERVER need, without identifying whether the host is using SSL, etc. You can add a trailing slash to that with trailingslashit if require, and it looks much cleaner too.

You may also like

LEAVE A COMMENT

@Asad_Umar یہ ملک خباستدانوں سے بھرا پڑا ہے۔ مجھے اُمیدہے آپ کی پارٹی کچھ اصل سیاستدان اس ملک کودےسکےگی جومحمدعلی جناح سے مجت کرنیوالے ہوں۔

Ways to Lazy Load Images to Speed Up Your WordPress Site https://t.co/hUfKWM0P2x

@Asad_Umar بے شک

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories