Returning current URL in WordPress

I am trying to implement canonical and hreflang tags in WordPress, but I cannot retrieve the current URL of the visited page.

I tried :

 <?php echo site_url(); ?>

But it returns https://www.example.com instead of https://www.example.com/current-page1


In case anyone else needs this. Below code should get the exact URL including parameters.

home_url($_SERVER['REQUEST_URI']);

You can echo or return it depending on your use case. e.g.

echo home_url($_SERVER['REQUEST_URI']);

or

return home_url($_SERVER['REQUEST_URI']);

The site_url() function returns the actual website root URL. Depending on where you are calling your URL you could try get_the_permalink() but a more surefire way would be to use the $wp->request method. Like this:

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

The main problem with this function is that the URL parameters are left out, so if your link is something like: http://example.com/test/?myparam=1 it will only return http://example.com/test/


If permalinks set to the plain:

$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";