WordPress – How to get a current URL?

How to get a current URL in WordPress?

Below you will find guide for:

  • a current URL of any WordPress page
  • a proper way to get homepage url
  • a propert way to get post url

A current URL of any WordPress page

The code below returns full url including protocol, hostname, part and the query part, for example https://www.tapdancingtocode.com/2020/12/wordpress-get-current-url/?utm_source=any.

In order for you not to use raw $_SERVER variables in lots of places in your code base, you can create a custom function inside your functions.php theme file.

function tap_get_current_url() {
    return (isset($_SERVER['HTTPS']) ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

A proper way to get WordPress homepage url

This is pretty straightforward in WordPress:

A proper way to get post url

While in a loop, you can use:

When you need to get a link to a post from any other place (outside the loop), just use get_the_permalink() and as the argument use either a post ID or the whole WP_Post object.


Sources:


Wrapping up

A video tutorial will be available shortly.

Until then,

Yours in coding.

Ivan


Image credits: Image by Dok Sev from Pixabay 

Leave a comment

Your email address will not be published. Required fields are marked *