Get Current Page URL in WordPress

Quick PHP code snacks to get the URL of the current page when working with WordPress—two code snippets with brief explanation.

If you are a WordPress developer, there are times when you need to grab the URL of the current page. I myself had made use of JavaScript to do so, that window.location.href stuff, you know.

But not every time you want to use JavScript for that, as you might need to get the URL straight and process it further to make a hyperlink, or anything else where you think JavaScript is not going to be useful. Then of course, you will need PHP to get this done.

PHP ways to grab the current URL

There are two ways to do get the current URL in WordPress with PHP. The first one is by making use of PHP’s $_SERVER:

<?php
  $current_url = "//" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>

The above one lets you get the URL without the prefix “http” or “https”. What it does is returns combining the host name, and the requested query parameters/strings, if any.

In case you want to get the complete URL with prefix as well, here is another two-line code snippet that comes in handy. Grab it from below:

<?php
  global $wp;
  $current_url = home_url( add_query_arg( array(), $wp->request ) );
?>

With the above code, you need not to worry what the prefix of the URL is (HTTP or HTTPS). It does the same job as the previous code snippet, but it also fetches the prefix associated with it. As you can see, it makes use of inbuilt functions in WordPress, and looks neat as well. Pretty handy, isn’t it?

How to use the code?

Here are some steps for beginners:

  1. Log into your WordPress Dashboard
  2. Navigate to the Editor in the Appearance section
  3. Look for the functions.php file, click it to make edits
  4. Copy and paste the code wherever you want, according to the need.

That was it. Feel free to share if you found this one helpful. Cheers!