window.location.href stuff, you know.
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
<?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:
- Log into your WordPress Dashboard
- Navigate to the Editor in the Appearance section
- Look for the
functions.phpfile, click it to make edits
- 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!